-
电脑安装protobufjs
npm install protobufjs -g -
准备proto文件
test.proto
syntax = "proto3";
message TestReq {
sint32 testid = 1;
}
message TestResp {
sint32 rtn = 1;
string msg = 2;
}
-
proto文件转proto.js
pbjs -t json-module -w commonjs -o proto.js ./*.proto -
项目引进protobufjs
npm install protobufjs --save -
使用proto.js封装请求
import protoRoot from "./proto/proto.js";
import protobuf from 'protobufjs';
let apiHost = "http://xxx.com";
let httpServicePost = function (url, api, req, cb) {
let ProtoReq = protoRoot.lookup(api + "Req");
let reqObj = ProtoReq.create(req);
let apiUrl = apiHost + url;
httpService.post(apiUrl, reqObj, {
transformRequest: function (data) {
let reqBuf = ProtoReq.encode(data).finish();
return reqBuf;
}
}).then(function (data) {
let ProtoResp = protoRoot.lookup(api + 'Resp')
let buf = protobuf.util.newBuffer(data.data);
let decodedResponse = ProtoResp.decode(buf)
if (process.env.NODE_ENV != 'production') {
console.log(reqObj);
console.log(decodedResponse)
}
cb ? cb(null, decodedResponse) : null;
}).catch((error) => {
// console.log(reqObj);
cb ? cb(error, null) : null;
});
}
// 接口使用
httpServicePost("/api/test", "Test", {testid:1}, function(err,data){
});