2020-04-05 00:57:34 +09:00
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as path from 'path';
|
|
|
|
import {Config, ConfigUser, configDefault} from './Config';
|
|
|
|
import {
|
|
|
|
apiFunctionsOf, OpenAPI, APIFunctions as APIFuncs,
|
|
|
|
ELParameterIn, SchemaType, Schemas, isObjectSchema,
|
|
|
|
} from './OpenAPI';
|
|
|
|
import {CodePrinter} from './CodePrinter';
|
|
|
|
|
|
|
|
function codegenIHandler(funcs: APIFuncs, config: Config, cp: CodePrinter) {
|
|
|
|
const {
|
2020-05-20 05:54:19 +09:00
|
|
|
schemasName, utilsTSPath, clientOnly,
|
2020-04-05 00:57:34 +09:00
|
|
|
} = config;
|
|
|
|
// import
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`import * as Schemas from './${schemasName}'`);
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('import {FullDate, StrictTypeParser as STP, APIPromise} ' +
|
|
|
|
`from '${utilsTSPath}'`);
|
2020-05-20 05:54:19 +09:00
|
|
|
if (!clientOnly) {
|
|
|
|
cp.writeln('import {RouterContext as CTX} from \'@koa/router\'');
|
|
|
|
}
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('import {AxiosResponse} from \'axios\'');
|
2020-04-15 07:45:51 +09:00
|
|
|
// api req, res types
|
|
|
|
cp.writeln(`export type TAPI = {`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
for (const [funcName, func] of Object.entries(funcs)) {
|
|
|
|
const {reqTypes, resTypes, method} = func;
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`${funcName}: {`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
// req
|
2020-04-15 07:45:51 +09:00
|
|
|
// req.path, ...
|
|
|
|
cp.writeln(`req: {`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
for (const _in of ELParameterIn) {
|
|
|
|
const paras = reqTypes[_in];
|
|
|
|
if (paras == null) continue;
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`${_in}: {`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
for (const [propName, schemaType] of Object.entries(paras)) {
|
|
|
|
cp.writeln(schemaType.forProp(propName)+';');
|
|
|
|
}
|
|
|
|
cp.writeln('};', -1);
|
|
|
|
}
|
|
|
|
// body
|
|
|
|
const {body} = reqTypes;
|
|
|
|
if (body != null) {
|
|
|
|
// PATCH's req body: Partial
|
|
|
|
let {typeName} = body;
|
|
|
|
if (method == 'patch') typeName = `Partial<${typeName}>`;
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`body${body.required ? '' : '?'}: ${typeName};`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('}', -1); // req END
|
2020-04-05 00:57:34 +09:00
|
|
|
// res
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`res: {`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
for (const [status, schema] of Object.entries(resTypes)) {
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(schema.required ?
|
|
|
|
`${schema.forProp(status)};`: `${status}: void;`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('}', -1); // res END
|
|
|
|
// operation END
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('}', -1);
|
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
// TAPI END
|
|
|
|
cp.writeln('}', -1);
|
|
|
|
// export IServerAPI
|
2020-05-20 05:54:19 +09:00
|
|
|
if (!clientOnly) {
|
|
|
|
cp.writeln('');
|
|
|
|
cp.writeln('type ValueOf<T> = T[keyof T];');
|
|
|
|
cp.writeln('type RServerAPI<T> = ValueOf<', 1);
|
|
|
|
cp.writeln('{[K in keyof T]: T[K] extends void ? [K, any?] : [K, T[K]]}>;',
|
|
|
|
-1, false);
|
|
|
|
cp.writeln('export type IServerAPI<IState=any> = {[K in keyof TAPI]:', 1);
|
|
|
|
cp.writeln(`(req: TAPI[K]['req'], state: IState, ctx: CTX) =>`, 1);
|
|
|
|
cp.writeln(`Promise<RServerAPI<TAPI[K]['res']>>}`, -2, false);
|
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
// return
|
2020-04-05 00:57:34 +09:00
|
|
|
return cp.end();
|
|
|
|
}
|
|
|
|
function codegenRouter(funcs: APIFuncs, config: Config, cp: CodePrinter) {
|
|
|
|
const {
|
2020-04-15 17:34:34 +09:00
|
|
|
schemasName, IHandlerName, ServerAPITSPath, utilsTSPath,
|
2020-04-05 00:57:34 +09:00
|
|
|
} = config;
|
|
|
|
// import
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`import * as Schemas from './${schemasName}'`);
|
2020-04-15 17:34:34 +09:00
|
|
|
cp.writeln(`import {IServerAPI} from './${IHandlerName}'`);
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln(`import * as Router from '@koa/router'`);
|
|
|
|
cp.writeln(
|
|
|
|
`import {FullDate, StrictTypeParser as STP} from '${utilsTSPath}'`);
|
|
|
|
cp.writeln(`import * as bodyParser from 'koa-body'`);
|
2020-04-15 17:34:34 +09:00
|
|
|
// api
|
|
|
|
cp.writeln(`\nimport api from '${ServerAPITSPath}'`);
|
|
|
|
cp.writeln(`type IState = typeof api extends IServerAPI<infer T> ? T : any;`);
|
2020-04-05 00:57:34 +09:00
|
|
|
// router
|
2020-04-15 17:34:34 +09:00
|
|
|
cp.writeln(`type CTX = Router.RouterContext<IState>;`);
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln(`\nconst router = new Router<IState>();`);
|
|
|
|
// function
|
2020-04-15 07:45:51 +09:00
|
|
|
const gcGetParams = {
|
|
|
|
path: (attr: string) => `ctx.params['${attr}']`,
|
|
|
|
query: (attr: string) => `ctx.query['${attr}']`,
|
|
|
|
header: (attr: string) => `ctx.headers['${attr}']`,
|
|
|
|
cookie: (attr: string) => `ctx.cookies.get('${attr}')`,
|
|
|
|
};
|
2020-04-05 00:57:34 +09:00
|
|
|
// route
|
|
|
|
for (const [funcName, func] of Object.entries(funcs)) {
|
|
|
|
const {
|
2020-04-15 07:45:51 +09:00
|
|
|
method, url, reqTypes,
|
2020-04-05 00:57:34 +09:00
|
|
|
} = func;
|
2020-04-08 20:17:57 +09:00
|
|
|
const isPartial = method === 'patch';
|
2020-04-05 00:57:34 +09:00
|
|
|
// TODO escape
|
|
|
|
const sURL = url.replace(/{(.*?)}/g, ':$1'); // {a} -> :a
|
|
|
|
let mid = '';
|
|
|
|
if (reqTypes.body) {
|
2020-04-15 07:45:51 +09:00
|
|
|
const {maxSize} = reqTypes.body; // TODO doc
|
2020-04-05 00:57:34 +09:00
|
|
|
const config = maxSize == null ? '' : `{jsonLimit: '${maxSize}'}`;
|
|
|
|
mid = `bodyParser(${config}), `;
|
|
|
|
}
|
|
|
|
cp.writeln(`router.${method}('${sURL}', ${mid}async ctx => {`, 1);
|
2020-04-08 20:17:57 +09:00
|
|
|
// req
|
2020-04-05 00:57:34 +09:00
|
|
|
if (Object.keys(reqTypes).length === 0) {
|
|
|
|
cp.writeln('const req = {};');
|
|
|
|
} else {
|
|
|
|
cp.writeln('let req;');
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('try {', 1);
|
|
|
|
cp.writeln('req = {', 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
// paras
|
|
|
|
for (const _in of ELParameterIn) {
|
|
|
|
const paras = reqTypes[_in];
|
|
|
|
if (paras == null) continue;
|
|
|
|
cp.writeln(`${_in}: {`, 1);
|
|
|
|
for (const [name, schema] of Object.entries(paras)) {
|
2020-04-15 07:45:51 +09:00
|
|
|
const pn = gcGetParams[_in](name);
|
2020-04-08 20:17:57 +09:00
|
|
|
const label = `req.${_in}`;
|
|
|
|
cp.writeln(`${name}: ${schema.stp(pn, label)},`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
|
|
|
cp.writeln('},', -1);
|
|
|
|
}
|
|
|
|
// body
|
|
|
|
const {body} = reqTypes;
|
|
|
|
if (body != null) {
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(
|
|
|
|
`body: ${body.stp('ctx.request.body', 'req.body', isPartial)}`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('}', -1);
|
|
|
|
cp.writeln('} catch(err) {', -1); cp.tab(1);
|
|
|
|
cp.writeln('if (err instanceof STP.BadValueError)', 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('return ctx.throw(400, err.toString());'); cp.tab(-1);
|
|
|
|
cp.writeln('throw err;');
|
|
|
|
cp.writeln('}', -1);
|
|
|
|
}
|
|
|
|
// call
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`const r = await api.${funcName}(req, ctx.state, ctx);`);
|
|
|
|
cp.writeln(`ctx.status = r[0];`);
|
|
|
|
cp.writeln(`ctx.body = r[1] ?? '';`);
|
|
|
|
// ctx END
|
|
|
|
cp.writeln('});', -1);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
|
|
|
cp.writeln('\nexport default router;');
|
|
|
|
return cp.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
function codegenClientAPI(funcs: APIFuncs, config: Config, cp: CodePrinter) {
|
2020-04-15 07:45:51 +09:00
|
|
|
const {IHandlerName, schemasName, utilsTSPath, validateStatus} = config;
|
2020-04-05 00:57:34 +09:00
|
|
|
// import
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`import {TAPI} from './${IHandlerName}'`);
|
|
|
|
cp.writeln(`import * as Schemas from './${schemasName}'`);
|
2020-05-24 01:23:42 +09:00
|
|
|
cp.writeln(`import {APIPromise, StrictTypeParser as STP, ` +
|
|
|
|
`qStringify} from '${utilsTSPath}'`);
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`import axios from 'axios'`);
|
|
|
|
cp.writeln('');
|
|
|
|
// type
|
2020-05-24 01:23:42 +09:00
|
|
|
cp.writeln(`type TSTP<T> = {[K in keyof T]: (data: any) =>`+
|
|
|
|
`T[K] extends void ? any : T[K]};`);
|
2020-04-05 00:57:34 +09:00
|
|
|
// axios
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('const $http = axios.create({', 1);
|
2020-05-24 01:23:42 +09:00
|
|
|
cp.writeln('validateStatus: () => true,');
|
|
|
|
cp.writeln('paramsSerializer: params => qStringify(params),');
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('});', -1);
|
|
|
|
// function
|
|
|
|
cp.writeln('\nfunction urlReplacer(url: string, ' +
|
|
|
|
'rules: {[_: string]: any}): string {', 1);
|
|
|
|
cp.writeln('for(const [attr, value] of Object.entries(rules))', 1);
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`url = url.replace('{'+attr+'}', value)`);
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('return url;', -1);
|
|
|
|
cp.writeln('};', -1);
|
|
|
|
// implementation
|
|
|
|
// export default
|
|
|
|
cp.writeln('\nexport default {', 1);
|
|
|
|
// set $baseURL
|
|
|
|
cp.writeln('set $baseURL(url: string) {', 1);
|
|
|
|
cp.writeln('$http.interceptors.request.use(async config => {', 1);
|
|
|
|
cp.writeln('config.baseURL = url;');
|
2020-04-11 02:22:47 +09:00
|
|
|
cp.writeln('return config;');
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('}, err => Promise.reject(err));', -1);
|
2020-04-11 02:22:47 +09:00
|
|
|
cp.writeln('},', -1);
|
2020-04-05 00:57:34 +09:00
|
|
|
// functions
|
|
|
|
for (const [funcName, func] of Object.entries(funcs)) {
|
2020-04-15 07:45:51 +09:00
|
|
|
const gcReq = (_in: string) => `TAPI['${funcName}']['req']['${_in}']`;
|
|
|
|
const {method, url, reqTypes, resTypes} = func;
|
2020-04-05 00:57:34 +09:00
|
|
|
const {
|
|
|
|
query, header, path, body,
|
|
|
|
} = reqTypes; // TODO cookie
|
|
|
|
// name
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`${funcName}: (`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
// paras
|
|
|
|
for (const _in of ELParameterIn) {
|
|
|
|
const paras = reqTypes[_in];
|
|
|
|
if (paras == null) continue;
|
|
|
|
let _required = false;
|
|
|
|
for (const {required} of Object.values(paras)) {
|
|
|
|
if (required) {
|
|
|
|
_required = true; break;
|
|
|
|
}
|
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`${_in}: ${gcReq(_in)}${_required ? '' : '={}'},`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
|
|
|
// body
|
|
|
|
if (body != null) {
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`body${body.required ? '' : '?'}: ${gcReq('body')},`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
// return value
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.tab(-1);
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`) => APIPromise.init($http({`, 1);
|
|
|
|
// req
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln(`method: '${method}',`);
|
|
|
|
const sURL = `'${url}'`;
|
|
|
|
cp.writeln(`url: ${path ? `urlReplacer(${sURL}, path)` : sURL},`);
|
|
|
|
if (query) cp.writeln('params: query,');
|
|
|
|
if (header) cp.writeln('header: header,');
|
|
|
|
if (body != null) cp.writeln('data: body,');
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('}), {', -1); cp.tab(1);
|
|
|
|
// stp
|
|
|
|
for (const [status, schema] of Object.entries(resTypes)) {
|
|
|
|
const label = `ClientAPI[${funcName}][${status}]`;
|
|
|
|
cp.writeln(`${status}: x => ${schema.stp('x', label)},`);
|
|
|
|
}
|
2020-05-20 05:54:19 +09:00
|
|
|
cp.writeln(`} as TSTP<TAPI['${funcName}']['res']>,`, -1);
|
|
|
|
cp.tab(1);
|
2020-04-15 07:45:51 +09:00
|
|
|
// kRsv
|
|
|
|
cp.writeln(`[${
|
|
|
|
Object.keys(resTypes).filter(validateStatus).join(', ')
|
|
|
|
}]),`, -1);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
2020-05-20 05:54:19 +09:00
|
|
|
cp.writeln('}', -1);
|
2020-04-05 00:57:34 +09:00
|
|
|
return cp.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
function codegenSchemas(schemas: Schemas, config: Config, cp: CodePrinter) {
|
|
|
|
const {utilsTSPath} = config;
|
|
|
|
// import
|
|
|
|
cp.writeln(
|
|
|
|
`import {FullDate, StrictTypeParser as STP} from '${utilsTSPath}'`);
|
|
|
|
// schema
|
2020-04-08 20:17:57 +09:00
|
|
|
for (const [typeName, schema] of Object.entries(schemas)) {
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln();
|
2020-04-05 00:57:34 +09:00
|
|
|
if (isObjectSchema(schema)) {
|
2020-04-15 07:45:51 +09:00
|
|
|
// interface
|
|
|
|
cp.writeln(`export interface ${typeName} {`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
const propTypes: [string, SchemaType][] = [];
|
2020-05-20 05:17:08 +09:00
|
|
|
const requireds = new Set(schema.required ?? []);
|
2020-04-05 00:57:34 +09:00
|
|
|
for (const [propName, prop] of Object.entries(schema.properties)) {
|
2020-05-20 05:17:08 +09:00
|
|
|
const propType = new SchemaType(prop, requireds.has(propName));
|
2020-04-05 00:57:34 +09:00
|
|
|
propTypes.push([propName, propType]);
|
|
|
|
cp.writeln(propType.forProp(propName)+';');
|
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('}', -1); // interface END
|
|
|
|
// const
|
|
|
|
cp.writeln(`export const ${typeName} = {`, 1);
|
|
|
|
// .from
|
|
|
|
cp.writeln(`from: (o: {[_: string]: any}): ${typeName} => ({`, 1);
|
2020-04-05 00:57:34 +09:00
|
|
|
for (const [n, t] of propTypes) {
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`${n}: ${t.stp(`o.${n}`, typeName+'.'+n)},`);
|
2020-04-08 20:17:57 +09:00
|
|
|
}
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('}),', -1);
|
2020-04-08 20:17:57 +09:00
|
|
|
// Partial
|
|
|
|
cp.writeln(
|
2020-04-15 07:45:51 +09:00
|
|
|
`Partial: (o: {[_: string]: any}): Partial<${typeName}> => {`, 1);
|
2020-04-08 20:17:57 +09:00
|
|
|
cp.writeln(`const r: Partial<${typeName}> = {};`);
|
|
|
|
const locPartial = `Partial<${typeName}>`;
|
|
|
|
for (const [n, t] of propTypes) {
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`if (o.${n} !== void 0) r.${n} = ${
|
2020-04-08 20:17:57 +09:00
|
|
|
t.stp(`o.${n}`, locPartial+'.'+n)};`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
2020-04-08 20:17:57 +09:00
|
|
|
cp.writeln('return r;');
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln('},', -1);
|
2020-04-15 07:15:54 +09:00
|
|
|
// fields
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`fields: [`, 1);
|
2020-04-15 07:15:54 +09:00
|
|
|
cp.writeln(propTypes.map(e => `'${e[0]}',`).join(' '));
|
2020-04-15 07:45:51 +09:00
|
|
|
cp.writeln(`] as Array<keyof ${typeName}>`, -1);
|
|
|
|
// end of const
|
2020-04-05 00:57:34 +09:00
|
|
|
cp.writeln('}', -1);
|
|
|
|
} else {
|
2020-04-08 20:17:57 +09:00
|
|
|
cp.writeln(`export type ${typeName} = ${SchemaType.typeNameOf(schema)}`);
|
2020-04-05 00:57:34 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// return
|
|
|
|
return cp.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function codegen(openAPI: OpenAPI, configUser: ConfigUser) {
|
2020-04-15 07:56:12 +09:00
|
|
|
const config: Config = Object.assign({}, configDefault, configUser);
|
2020-04-05 00:57:34 +09:00
|
|
|
// prepare
|
|
|
|
fs.mkdirSync(config.outputDir, {recursive: true});
|
|
|
|
const apiFuncs = apiFunctionsOf(openAPI);
|
|
|
|
const gCP = (fn: string) => new CodePrinter(
|
|
|
|
fs.createWriteStream(path.join(config.outputDir, fn+'.ts')),
|
|
|
|
config.indentString,
|
|
|
|
);
|
|
|
|
const ps: Promise<any>[] = [];
|
|
|
|
// write files
|
|
|
|
// handler
|
|
|
|
ps.push(codegenIHandler(apiFuncs, config, gCP(config.IHandlerName)));
|
|
|
|
// server
|
2020-05-20 05:17:08 +09:00
|
|
|
if (!config.clientOnly) {
|
|
|
|
ps.push(codegenRouter(apiFuncs, config, gCP(config.routerName)));
|
|
|
|
}
|
2020-04-05 00:57:34 +09:00
|
|
|
// client
|
|
|
|
ps.push(codegenClientAPI(apiFuncs, config, gCP(config.ClientAPIName)));
|
|
|
|
// schema
|
|
|
|
const schemas = openAPI.components?.schemas;
|
|
|
|
if (schemas != null) {
|
|
|
|
ps.push(codegenSchemas(schemas, config, gCP(config.schemasName)));
|
|
|
|
}
|
|
|
|
// return
|
|
|
|
return Promise.all(ps);
|
|
|
|
}
|