问题描述
使用动态代码生成时,我们可以使用以下方式加载.proto
文件:
const packageDefinition: PackageDefinition = protoLoader.loadSync(PROTO_PATH,{
keepCase: true,longs: String,enums: String,defaults: true,oneofs: true,includeDirs: [__dirname],});
我们可以设置keepCase
选项来保留字段名称,不要将它们更改为驼峰式。还有enums
选项,因此我们可以使用代表枚举的字符串表示。
现在,我正在使用静态代码生成。面对以上两个问题,这是我的服务的方法实现:
public async getTopics(call: ServerUnaryCall<GetTopicsRequest>,callback: sendUnaryData<GetTopicsResponse>) {
const obj = call.request.toObject();
const url = `${config.CNODE_API_URL}/topics`;
const params = {
page: obj.page || obj.page + 1,tab: (getEnumKeyByEnumValue(Tab,obj.tab) || '').toLowerCase(),mdrender: (getEnumKeyByEnumValue(Mdrender,obj.mdrender) || 'true').toLowerCase(),limit: obj.limit,};
try {
const res = await axios.get(url,{ params });
const data = res.data;
// console.log(data);
const topicsResponse = new GetTopicsResponse();
data.data.forEach((po,i) => {
const topic = new Topic();
topic.setId(po.id);
topic.setAuthorId(po.author_id);
topic.setTab(Tab[po.tab.toUpperCase() as keyof typeof Tab]);
topic.setContent(po.content);
topic.setTitle(po.title);
topic.setLastReplyAt(po.last_reply_at);
topic.setGood(po.good);
topic.setTop(po.top);
topic.setReplyCount(po.reply_count);
topic.setVisitCount(po.visit_count);
topic.setCreateAt(po.create_at);
const author = new UserBase();
author.setLoginname(po.author.loginname);
author.setAvatarUrl(po.avatar_url);
topic.setAuthor(author);
topicsResponse.addData(topic,i);
});
topicsResponse.setSuccess(data.success);
callback(null,topicsResponse);
} catch (error) {
console.log(error);
const metadata = new Metadata({ idempotentRequest: true });
metadata.set('params',JSON.stringify(params));
metadata.set('url',url);
const ErrGetTopics: ServiceError = { code: status.INTERNAL,name: 'getTopicsError',message: 'call CNode API failed',metadata };
callback(ErrGetTopics,null);
}
}
这是我面临的问题:
- 使用proto3时无法设置默认值,想要将
page
参数的默认值设置为1
,而不是0
。 - 我需要将枚举从数字转换为手动表示的字符串。
- RESTful API响应中的字段为蛇形,但是
protoc
,grpc_tools_node_protoc
和grpc_tools_node_protoc_ts
插件会生成具有驼峰式大小写字段的模型。所以我想保留情况。 - 如您所见,水合过程既不方便又无聊。我需要打电话给setter来为字段一一设置值。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)