Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow configuring the path of the openapi json spec #11

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ export const swagger =
version = '4.18.2',
excludeStaticFile = true,
path = '/swagger' as Path,
specPathname = 'json',
exclude = []
}: ElysiaSwaggerConfig<Path> = {
documentation: {},
version: '4.18.2',
excludeStaticFile: true,
path: '/swagger' as Path,
specPathname: 'json',
exclude: []
}
) =>
Expand All @@ -33,6 +35,10 @@ export const swagger =
version: '0.0.0',
...documentation.info
}

if (specPathname.startsWith('/')) {
specPathname = specPathname.slice(1)
}

app.get(path, (context) => {
return new Response(
Expand All @@ -58,7 +64,7 @@ export const swagger =
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: '${path}/json',
url: '${path}/${specPathname}',
dom_id: '#swagger-ui',
});
};
Expand All @@ -73,7 +79,7 @@ export const swagger =
)
}).route(
'GET',
`${path}/json`,
`${path}/${specPathname}`,
(context) =>
({
openapi: '3.0.3',
Expand Down
8 changes: 8 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ export interface ElysiaSwaggerConfig<Path extends string = '/swagger'> {
* @default '/swagger'
*/
path?: Path
/**
* The pathname for the OpenAPI spec, which will be appended to the path option.
*
* @example 'openapi.json' => '/swagger/openapi.json'
*
* @default 'json'
*/
specPathname?: string
/**
* Paths to exclude from Swagger endpoint
*
Expand Down
13 changes: 13 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,17 @@ describe('Swagger', () => {
const res = await app.handle(req('/v2/swagger'))
expect(res.status).toBe(200)
})

it('use custom spec path', async () => {
const app = new Elysia().use(
swagger({
path: '/v2/swagger',
specPathname: 'openapi.json'
})
)

const res = await app.handle(req('/v2/swagger/openapi.json'))
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toContain('application/json')
})
})