使用OpenAPI Generator生成TypeScript-Fetch客户端时,JsonPatchDocument序列化及请求参数缺失问题求助
我自己维护着应用的服务端和客户端,服务端用的是.NET 9 WebAPI,还开启了OpenAPI/Swagger支持,一直用Open Collective提供的openapi_generator来生成TypeScript-Fetch风格的REST客户端。最近想尝试用JsonPatchDocument实现实体的部分更新,不用每次都传整个对象过去,结果遇到了头疼的问题:
问题详情
- 服务端用了
JsonPatchDocument之后,生成器确实创建了对应的客户端类型,比如FriendDataJsonPatchDocument,但我只能通过直接对象赋值的方式创建它:
const patch: FriendDataJsonPatchDocument = { operations: [{ op: "Replace", path: "/name", value: name }] }
- 调用生成的API方法时,我是这么写的:
await api.patchFriend({ id: friendId, friendDataJsonPatchDocument: patch })
- 抓包后发现,序列化后的JSON里既没有
id字段,连operations集合也不见了! - 查看生成的
PatchFriendRequest接口,发现了问题所在:
export interface PatchFriendRequest { id: string; friendDataJsonPatchDocument?: Omit<FriendDataJsonPatchDocument, 'operations'>; }
这里明显能看到operations被故意排除了,而且id也没被正确序列化进去。
我用的生成命令是:
openapi-generator-cli generate --enable-post-process-file -i https://localhost:32772/swagger/v1/swagger.json -g typescript-fetch -o src/clients/api/rest --additional-properties=withInterfaces=true,stringEnums=true,generateSourceCodeOnly=true
版本是v2.20.2。
可行解决方案
1. 排查Swagger规范的正确性
首先建议你直接访问服务端的Swagger JSON文件,搜索FriendDataJsonPatchDocument相关的Schema定义。.NET的JsonPatchDocument在Swagger里应该生成符合RFC 6902的数组类型(直接是操作对象的数组),而不是嵌套operations属性的对象。如果服务端生成的Schema是后者,那生成器就会误解结构,进而出现自动Omitoperations的问题。
如果Schema不对,需要调整服务端的Swagger配置,确保JsonPatchDocument的Schema正确生成。
2. 调整生成器的配置参数
针对TypeScript-Fetch生成器,有几个参数可以尝试调整:
- 添加
useSingleRequestParameter=true到additional-properties中,这个参数会让请求参数的处理更直接,避免自动剔除属性。修改后的生成命令:
openapi-generator-cli generate --enable-post-process-file -i https://localhost:32772/swagger/v1/swagger.json -g typescript-fetch -o src/clients/api/rest --additional-properties=withInterfaces=true,stringEnums=true,generateSourceCodeOnly=true,useSingleRequestParameter=true
- 考虑升级OpenAPI Generator的版本,v2.20.2确实比较老旧了,新版本(比如v7及以上)对
JsonPatch的支持更完善,很多这类序列化问题都已经修复。
3. 临时手动修复生成代码(应急方案)
如果暂时没法升级或调整配置,可以手动修改生成的PatchFriendRequest接口,把Omit修饰符去掉:
export interface PatchFriendRequest { id: string; friendDataJsonPatchDocument?: FriendDataJsonPatchDocument; }
同时要检查生成的patchFriend方法定义,确认id是作为路径参数传递的(如果你的服务端接口是把id放在URL路径里的话),避免生成器错误地把它放到请求体中。
4. 确认服务端的参数绑定
最后还要检查服务端的PatchFriend接口参数绑定是否正确:
id如果是路径参数,要加[FromRoute]标记;JsonPatchDocument要加[FromBody]标记。
参数绑定错误也会导致客户端生成的代码出现参数传递异常。
内容来源于stack exchange

