Lap*_*ill 2 typescript openapi
我有 openApi 生成器生成的类。每个类方法都以 HTTP 方法名称结尾,例如“deleteBookUsingDELETE”或“getBookUsingGET”。对于类中的每个方法都应该创建相应的react-query hook。当方法以 GET 结尾时,应使用 useQuery 挂钩,其余 HTTP 方法使用 useMutation。问题是:如何创建类型安全适配器?openApi 生成的类示例(已删除实现)。
export class MetricControllerApi extends runtime.BaseAPI {
async byEndpointUsingGETRaw(requestParameters: ByEndpointUsingGETRequest): Promise<runtime.ApiResponse<MetricDtoResponse>> {
}
async byEndpointUsingGET(requestParameters: ByEndpointUsingGETRequest): Promise<MetricDtoResponse> {
}
async byOwnerUsingGETRaw(requestParameters: ByOwnerUsingGETRequest): Promise<runtime.ApiResponse<MetricResponse>> {
}
async byOwnerUsingGET(requestParameters: ByOwnerUsingGETRequest): Promise<MetricResponse> {
}
async byTopicUsingGETRaw(requestParameters: ByTopicUsingGETRequest): Promise<runtime.ApiResponse<MetricResponse>> {
}
async byTopicUsingGET(requestParameters: ByTopicUsingGETRequest): Promise<MetricResponse> {
}
}
Run Code Online (Sandbox Code Playgroud)
我设法编写的不是类型安全的适配器
export class Adapter<T extends object> {
constructor(private readonly controllerApiInst: T) {
}
generate(): Record<keyof T, CallableFunction> {
const prototype = Object.getPrototypeOf(this.controllerApiInst);
const res = (Object.getOwnPropertyNames(prototype) as (keyof T)[])
.filter(fieldOrMethod => {
if (typeof prototype[fieldOrMethod] === 'function') {
return true;
}
})
.reduce((acc: any, v: keyof T) => {
acc[v] = <P, R>(req: P): R => {
return (this.controllerApiInst[v] as CallableFunction)(req);
};
return acc;
}, { ...prototype });
return res;
}
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
const configuration = new Configuration({
basePath: 'test'
});
export const metricsController= new MetricControllerApi(configuration);
const check = new Adapter(metricsController);
const res = check.generate();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4432 次 |
| 最近记录: |