diff --git a/CHANGELOG.md b/CHANGELOG.md index e69de29..a88774d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +# 0.0.0-experimental.1 - 12 Nov 2022 +Improvement: +- Auto infers path params if schema is presented +- Auto infers path params now merge with schema.params diff --git a/example/index.ts b/example/index.ts index b8299fa..376f395 100644 --- a/example/index.ts +++ b/example/index.ts @@ -1,35 +1,19 @@ import { KingWorld, t } from 'kingworld' - +// ? @kingworldjs/schema import swagger from '../src/index' const app = new KingWorld() - .use(swagger, { - // path: '/v2/swagger', - // swagger: { - // info: { - // title: 'Hello World', - // version: '0.0.0' - // } - // } - }) + .use(swagger) .get('/', () => 'hi') .get('/unpath/:id', ({ params: { id } }) => id) - .get('/unpath/:id/:name', ({ params: { id } }) => id) .post( '/json/:id', ({ body, params: { id }, query: { name } }) => ({ ...body, - id, - name + id }), { schema: { - params: t.Object({ - id: t.String() - }), - query: t.Object({ - name: t.String() - }), body: t.Object({ username: t.String(), password: t.String() @@ -37,12 +21,12 @@ const app = new KingWorld() response: t.Object({ username: t.String(), password: t.String(), - id: t.String(), - name: t.String() + id: t.String() }) } } ) + .get('/unpath/:id/:name', ({ params: { id } }) => id) .post('/json', ({ body }) => body, { schema: { body: t.Object({ diff --git a/package.json b/package.json index 21f5a3e..5dbc5b5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kingworldjs/swagger", - "version": "0.0.0-experimental.0", + "version": "0.0.0-experimental.1", "description": "A plugin for kingworld that auto-generate Swagger page", "author": { "name": "saltyAom", diff --git a/src/index.ts b/src/index.ts index 760e8e9..e14fac0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,16 +38,31 @@ const filterPaths = ( Object.keys(value).forEach((method) => { const schema = value[method] - if (key.includes('{') && !schema.parameters) - schema.parameters = key - .split('/') - .filter((x) => x.startsWith('{')) - .map((x) => ({ - in: 'path', - name: x.slice(1, x.length - 1), - type: 'string', - required: true - })) + if (key.includes('{')) { + if (!schema.parameters) schema.parameters = [] + + schema.parameters = [ + ...key + .split('/') + .filter( + (x) => + x.startsWith('{') && + !schema.parameters.find( + (params: Record) => + params.in === 'path' && + params.name === + x.slice(1, x.length - 1) + ) + ) + .map((x) => ({ + in: 'path', + name: x.slice(1, x.length - 1), + type: 'string', + required: true + })), + ...schema.parameters + ] + } if (!schema.responses) schema.responses = { @@ -63,7 +78,7 @@ const filterPaths = ( /** * A plugin for [kingworld](https://github.com/saltyaom/kingworld) that auto-generate Swagger page. - * + * * @see https://github.com/saltyaom/kingworld-swagger */ export const swagger = (