-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
GenerateHttpClientCmd.ts
189 lines (153 loc) · 5.61 KB
/
GenerateHttpClientCmd.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import {CliFs, Command, CommandProvider, Inject, Type} from "@tsed/cli-core";
import {Constant, InjectorService} from "@tsed/di";
import {importPackage, isString} from "@tsed/core";
import {camelCase} from "change-case";
import path, {join, resolve} from "path";
import {generateApi, Hooks, RawRouteInfo, RouteNameInfo} from "swagger-typescript-api";
export interface GenerateHttpClientCtx {
output: string;
type: "axios" | "fetch";
name: string;
suffix: string;
}
export interface GenerateHttpClientOpts {
hooks?: Partial<Hooks>;
transformOperationId?(operationId: string, routeNameInfo: RouteNameInfo, raw: RawRouteInfo): string;
}
@Command({
name: "generate-http-client",
description: "Generate the client API from swagger spec",
options: {
"-s, --suffix <suffix>": {
required: false,
type: String,
defaultValue: "Model",
description: "The suffix applied on model"
},
"-t, --type <type>": {
required: false,
type: String,
defaultValue: "axios",
description: "The client type by the Http client (axios or fetch)"
},
"-n, --name <name>": {
required: false,
type: String,
defaultValue: "ApiClient",
description: "The class name of the generated client"
},
"-o, --output <output>": {
required: true,
type: String,
description: "Path to generate files"
}
}
})
export class GenerateHttpClientCmd implements CommandProvider {
@Inject()
injector: InjectorService;
@Inject()
protected fs: CliFs;
@Constant("server")
protected serverModule: Type<any>;
@Constant("httpClient", {hooks: {}})
protected options: Partial<GenerateHttpClientOpts>;
$mapContext($ctx: GenerateHttpClientCtx) {
return {...$ctx, output: resolve(join(process.cwd(), $ctx.output))};
}
$exec($ctx: GenerateHttpClientCtx) {
return [
{
title: "generate client",
task: () => this.generate($ctx)
}
];
}
private async loadPlatformModule(): Promise<any> {
let platform = await importPackage("@tsed/platform-express", undefined, true);
if (platform) {
return platform.PlatformExpress;
}
platform = await importPackage("@tsed/platform-koa", undefined, true);
if (platform) {
return platform.PlatformKoa;
}
throw new Error("Unsupported platform. Please use Express.js or Koa.js platform.");
}
private async generate($ctx: GenerateHttpClientCtx) {
const Platform = await this.loadPlatformModule();
const {SwaggerService} = await importPackage("@tsed/swagger");
const platform: {
injector: InjectorService;
stop: () => Promise<any>;
} = await Platform.bootstrap(this.serverModule, {
logger: {level: "off"},
mongoose: [],
redis: [],
ioredis: []
});
const swaggerService = platform.injector.get<any>(SwaggerService)!;
const confs = platform.injector.settings.get("swagger", []);
await this.fs.raw.remove($ctx.output);
await this.fs.ensureDir($ctx.output);
const promises = confs.map(async (conf) => {
const spec = await swaggerService.getOpenAPISpec(conf);
await this.generateFromSpec(spec, conf, $ctx);
});
await Promise.all(promises);
await platform.stop();
}
private async generateFromSpec(spec: any, conf: any, $ctx: GenerateHttpClientCtx) {
const operationIdMode = !conf.operationId || conf.operationId === "%c_%m" ? "underscore" : "default";
const {files} = await generateApi({
name: `${$ctx.name}.ts`,
httpClientType: $ctx.type,
spec: spec as any,
moduleNameIndex: 1,
typeSuffix: $ctx.suffix,
unwrapResponseData: true,
hooks: {
onCreateRouteName: (routeNameInfo: RouteNameInfo, rawRouteInfo: RawRouteInfo) =>
this.createRouteName(routeNameInfo, rawRouteInfo, operationIdMode),
onParseSchema: this.onParseSchema.bind(this),
...this.options.hooks
}
} as any);
const promises = files.map(({content, name}) => {
content = content
.replace("class Api", `class ${$ctx.name}`)
.replace(".then((response) => response.data)", ".then((response) => response.data as T)")
.replace('requestParams.headers.common = { Accept: "*/*" };', "")
.replace("requestParams.headers.post = {};", "")
.replace("requestParams.headers.put = {};", "")
.replace("(this.instance.defaults.headers || {})", "((this.instance.defaults.headers || {}) as any)");
console.log(`${$ctx.output}/${name}`, path.resolve(`${$ctx.output}/${name}`));
return this.fs.writeFile(`${$ctx.output}/${name}`, content, {encoding: "utf8"});
});
return Promise.all(promises);
}
private onParseSchema(originalSchema: any, parsedSchema: any) {
const {content} = parsedSchema;
if (isString(content)) {
if (content.includes("null") && content.includes("any") && content.includes("Record")) {
parsedSchema.content = "any";
}
parsedSchema.content = parsedSchema.content.replace("object", "Record<string, any>");
}
return parsedSchema;
}
private createRouteName(routeNameInfo: RouteNameInfo, raw: RawRouteInfo, mode: "default" | "underscore" = "default") {
let operationId = "";
if (mode === "underscore") {
operationId = raw.operationId.split("_")[1];
}
operationId = operationId || raw.operationId.replace(raw.moduleName, "");
const name = camelCase(
this.options.transformOperationId ? this.options.transformOperationId(operationId, routeNameInfo, raw) : operationId
);
routeNameInfo.usage = name;
routeNameInfo.original = name;
raw.operationId = name;
return routeNameInfo;
}
}