0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-06 20:40:08 -05:00
logto/packages/core/src/routes/swagger.ts

65 lines
1.8 KiB
TypeScript
Raw Normal View History

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) {
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 [
`/api${path}`,
2021-07-23 10:10:54 -05:00
Object.fromEntries(
methods.map<[string, OpenAPIV3.OperationObject]>((method) => [
method.toLowerCase(),
{
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;
return next();
});
2021-07-23 10:10:54 -05:00
}