2021-09-16 10:48:06 -05:00
|
|
|
import { toTitle } from '@silverhand/essentials';
|
2021-09-01 04:35:23 -05:00
|
|
|
import { IMiddleware } from 'koa-router';
|
2021-07-23 10:10:54 -05:00
|
|
|
import { OpenAPIV3 } from 'openapi-types';
|
2021-08-29 22:30:54 -05:00
|
|
|
|
2021-07-23 10:10:54 -05:00
|
|
|
import { isGuardMiddleware, WithGuardConfig } from '@/middleware/koa-guard';
|
|
|
|
import { zodTypeToSwagger } from '@/utils/zod';
|
|
|
|
|
2021-09-01 04:35:23 -05:00
|
|
|
import { AnonymousRouter } from './types';
|
|
|
|
|
|
|
|
export default function swaggerRoutes<T extends AnonymousRouter>(router: T) {
|
2021-07-29 13:21:47 -05:00
|
|
|
router.get('/swagger.json', async (ctx, next) => {
|
2021-07-23 10:10:54 -05:00
|
|
|
const routes = ctx.router.stack.map(({ path, stack, methods }) => {
|
|
|
|
const guard = stack.find((function_): function_ is WithGuardConfig<IMiddleware> =>
|
|
|
|
isGuardMiddleware(function_)
|
|
|
|
);
|
2022-01-27 06:26:34 -05:00
|
|
|
|
2021-07-23 10:10:54 -05:00
|
|
|
return { path, methods, guard };
|
|
|
|
});
|
|
|
|
|
|
|
|
const paths = Object.fromEntries(
|
|
|
|
routes.map<[string, OpenAPIV3.PathItemObject]>(({ path, methods, guard }) => {
|
|
|
|
const body = guard?.config.body;
|
|
|
|
|
|
|
|
return [
|
2021-07-29 13:21:47 -05:00
|
|
|
`/api${path}`,
|
2021-07-23 10:10:54 -05:00
|
|
|
Object.fromEntries(
|
|
|
|
methods.map<[string, OpenAPIV3.OperationObject]>((method) => [
|
|
|
|
method.toLowerCase(),
|
|
|
|
{
|
2021-07-29 13:21:47 -05:00
|
|
|
tags: [toTitle(path.split('/')[1] ?? 'General')],
|
2021-07-23 10:10:54 -05:00
|
|
|
requestBody: body && {
|
|
|
|
required: true,
|
|
|
|
content: {
|
|
|
|
'application/json': {
|
|
|
|
schema: zodTypeToSwagger(body),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
responses: {
|
|
|
|
'200': {
|
|
|
|
description: 'OK',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
])
|
|
|
|
),
|
|
|
|
];
|
|
|
|
})
|
|
|
|
);
|
|
|
|
|
|
|
|
const document: OpenAPIV3.Document = {
|
|
|
|
openapi: '3.0.1',
|
|
|
|
info: {
|
|
|
|
title: 'Logto Core',
|
|
|
|
version: '0.1.0',
|
|
|
|
},
|
|
|
|
paths,
|
|
|
|
};
|
|
|
|
|
|
|
|
ctx.body = document;
|
|
|
|
|
2021-07-29 13:21:47 -05:00
|
|
|
return next();
|
|
|
|
});
|
2021-07-23 10:10:54 -05:00
|
|
|
}
|