mirror of
https://github.com/zoriya/elysia-swagger.git
synced 2025-12-06 00:36:10 +00:00
🧹 chore: support optional path parameter
This commit is contained in:
@@ -19,4 +19,7 @@ CHANGELOG.md
|
|||||||
.eslintrc.js
|
.eslintrc.js
|
||||||
tsconfig.cjs.json
|
tsconfig.cjs.json
|
||||||
tsconfig.esm.json
|
tsconfig.esm.json
|
||||||
|
tsconfig.dts.json
|
||||||
|
|
||||||
|
src
|
||||||
|
build.ts
|
||||||
|
|||||||
7
.prettierrc
Normal file
7
.prettierrc
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"useTabs": true,
|
||||||
|
"tabWidth": 4,
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "none"
|
||||||
|
}
|
||||||
@@ -1,4 +1,9 @@
|
|||||||
|
|
||||||
|
# 1.1.0-rc.0 - 12 Jul 2024
|
||||||
|
Change:
|
||||||
|
- Add support for Elysia 1.1
|
||||||
|
|
||||||
|
|
||||||
# 1.0.2 - 18 Mar 2024
|
# 1.0.2 - 18 Mar 2024
|
||||||
Change:
|
Change:
|
||||||
- Add support for Elysia 1.0
|
- Add support for Elysia 1.0
|
||||||
|
|||||||
37
build.ts
Normal file
37
build.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { $ } from 'bun'
|
||||||
|
import { build, type Options } from 'tsup'
|
||||||
|
|
||||||
|
await $`rm -rf dist`
|
||||||
|
|
||||||
|
const tsupConfig: Options = {
|
||||||
|
entry: ['src/**/*.ts'],
|
||||||
|
splitting: false,
|
||||||
|
sourcemap: false,
|
||||||
|
clean: true,
|
||||||
|
bundle: true
|
||||||
|
} satisfies Options
|
||||||
|
|
||||||
|
await Promise.all([
|
||||||
|
// ? tsup esm
|
||||||
|
build({
|
||||||
|
outDir: 'dist',
|
||||||
|
format: 'esm',
|
||||||
|
target: 'node20',
|
||||||
|
cjsInterop: false,
|
||||||
|
...tsupConfig
|
||||||
|
}),
|
||||||
|
// ? tsup cjs
|
||||||
|
build({
|
||||||
|
outDir: 'dist/cjs',
|
||||||
|
format: 'cjs',
|
||||||
|
target: 'node20',
|
||||||
|
// dts: true,
|
||||||
|
...tsupConfig
|
||||||
|
})
|
||||||
|
])
|
||||||
|
|
||||||
|
await $`tsc --project tsconfig.dts.json`
|
||||||
|
|
||||||
|
await Promise.all([$`cp dist/*.d.ts dist/cjs`])
|
||||||
|
|
||||||
|
process.exit()
|
||||||
@@ -39,7 +39,6 @@ const app = new Elysia()
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.use(plugin)
|
// .use(plugin)
|
||||||
|
.get('/id/:id?', 'a')
|
||||||
.listen(3000)
|
.listen(3000)
|
||||||
|
|
||||||
console.log(app.routes)
|
|
||||||
|
|||||||
62
package.json
62
package.json
@@ -1,21 +1,48 @@
|
|||||||
{
|
{
|
||||||
"name": "@elysiajs/swagger",
|
"name": "@elysiajs/swagger",
|
||||||
"version": "1.0.4",
|
"version": "1.1.0-rc.1",
|
||||||
"description": "Plugin for Elysia to auto-generate Swagger page",
|
"description": "Plugin for Elysia to auto-generate Swagger page",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "saltyAom",
|
"name": "saltyAom",
|
||||||
"url": "https://github.com/SaltyAom",
|
"url": "https://github.com/SaltyAom",
|
||||||
"email": "saltyaom@gmail.com"
|
"email": "saltyaom@gmail.com"
|
||||||
},
|
},
|
||||||
"main": "./dist/index.js",
|
"main": "./dist/cjs/index.js",
|
||||||
"exports": {
|
"module": "./dist/index.mjs",
|
||||||
"bun": "./dist/index.js",
|
|
||||||
"node": "./dist/cjs/index.js",
|
|
||||||
"require": "./dist/cjs/index.js",
|
|
||||||
"import": "./dist/index.js",
|
|
||||||
"default": "./dist/index.js"
|
|
||||||
},
|
|
||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
|
"exports": {
|
||||||
|
"./package.json": "./package.json",
|
||||||
|
".": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"import": "./dist/index.mjs",
|
||||||
|
"require": "./dist/cjs/index.js"
|
||||||
|
},
|
||||||
|
"./types": {
|
||||||
|
"types": "./dist/types.d.ts",
|
||||||
|
"import": "./dist/types.mjs",
|
||||||
|
"require": "./dist/cjs/types.js"
|
||||||
|
},
|
||||||
|
"./utils": {
|
||||||
|
"types": "./dist/utils.d.ts",
|
||||||
|
"import": "./dist/utils.mjs",
|
||||||
|
"require": "./dist/cjs/utils.js"
|
||||||
|
},
|
||||||
|
"./scalar": {
|
||||||
|
"types": "./dist/scalar/index.d.ts",
|
||||||
|
"import": "./dist/scalar/index.mjs",
|
||||||
|
"require": "./dist/cjs/scalar/index.js"
|
||||||
|
},
|
||||||
|
"./scalar/theme": {
|
||||||
|
"types": "./dist/scalar/theme.d.ts",
|
||||||
|
"import": "./dist/scalar/theme.mjs",
|
||||||
|
"require": "./dist/cjs/scalar/theme.js"
|
||||||
|
},
|
||||||
|
"./scalar/types": {
|
||||||
|
"types": "./dist/scalar/types/index.d.ts",
|
||||||
|
"import": "./dist/scalar/types/index.mjs",
|
||||||
|
"require": "./dist/cjs/scalar/types/index.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"elysia",
|
"elysia",
|
||||||
"swagger"
|
"swagger"
|
||||||
@@ -31,22 +58,21 @@
|
|||||||
"dev": "bun run --watch example/index.ts",
|
"dev": "bun run --watch example/index.ts",
|
||||||
"test": "bun test && npm run test:node",
|
"test": "bun test && npm run test:node",
|
||||||
"test:node": "npm install --prefix ./test/node/cjs/ && npm install --prefix ./test/node/esm/ && node ./test/node/cjs/index.js && node ./test/node/esm/index.js",
|
"test:node": "npm install --prefix ./test/node/cjs/ && npm install --prefix ./test/node/esm/ && node ./test/node/cjs/index.js && node ./test/node/esm/index.js",
|
||||||
"build": "rimraf dist && tsc --project tsconfig.esm.json && tsc --project tsconfig.cjs.json",
|
"build": "bun build.ts",
|
||||||
"release": "npm run build && npm run test && npm publish --access public"
|
"release": "npm run build && npm run test && npm publish --access public"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"elysia": ">= 1.0.2"
|
"elysia": ">= 1.1.0-rc.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@apidevtools/swagger-parser": "^10.1.0",
|
"@apidevtools/swagger-parser": "^10.1.0",
|
||||||
"@scalar/api-reference": "^1.12.5",
|
"@scalar/api-reference": "^1.12.5",
|
||||||
"@types/bun": "^1.0.4",
|
"@types/bun": "1.1.6",
|
||||||
"@types/lodash.clonedeep": "^4.5.7",
|
"@types/lodash.clonedeep": "^4.5.9",
|
||||||
"@types/node": "^20.1.4",
|
"elysia": ">= 1.1.0-rc.2",
|
||||||
"elysia": "1.0.2",
|
"eslint": "9.6.0",
|
||||||
"eslint": "^8.40.0",
|
"tsup": "^8.1.0",
|
||||||
"rimraf": "4.3",
|
"typescript": "^5.5.3"
|
||||||
"typescript": "^5.0.4"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"lodash.clonedeep": "^4.5.0",
|
"lodash.clonedeep": "^4.5.0",
|
||||||
|
|||||||
168
src/index.ts
168
src/index.ts
@@ -1,126 +1,118 @@
|
|||||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||||
import { type Elysia, type InternalRoute } from 'elysia'
|
import { Elysia, type InternalRoute } from "elysia";
|
||||||
|
|
||||||
import { SwaggerUIRender } from './swagger'
|
import { SwaggerUIRender } from "./swagger";
|
||||||
import { ScalarRender } from './scalar'
|
import { ScalarRender } from "./scalar";
|
||||||
|
|
||||||
import { filterPaths, registerSchemaPath } from './utils'
|
import { filterPaths, registerSchemaPath } from "./utils";
|
||||||
|
|
||||||
import type { OpenAPIV3 } from 'openapi-types'
|
import type { OpenAPIV3 } from "openapi-types";
|
||||||
import type { ReferenceConfiguration } from './scalar/types'
|
import type { ReferenceConfiguration } from "./scalar/types";
|
||||||
import type { ElysiaSwaggerConfig } from './types'
|
import type { ElysiaSwaggerConfig } from "./types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Plugin for [elysia](https://github.com/elysiajs/elysia) that auto-generate Swagger page.
|
* Plugin for [elysia](https://github.com/elysiajs/elysia) that auto-generate Swagger page.
|
||||||
*
|
*
|
||||||
* @see https://github.com/elysiajs/elysia-swagger
|
* @see https://github.com/elysiajs/elysia-swagger
|
||||||
*/
|
*/
|
||||||
export const swagger =
|
export const swagger = async <Path extends string = "/swagger">(
|
||||||
<Path extends string = '/swagger'>(
|
|
||||||
{
|
{
|
||||||
provider = 'scalar',
|
provider = "scalar",
|
||||||
scalarVersion = 'latest',
|
scalarVersion = "latest",
|
||||||
scalarCDN = '',
|
scalarCDN = "",
|
||||||
scalarConfig = {},
|
scalarConfig = {},
|
||||||
documentation = {},
|
documentation = {},
|
||||||
version = '5.9.0',
|
version = "5.9.0",
|
||||||
excludeStaticFile = true,
|
excludeStaticFile = true,
|
||||||
path = '/swagger' as Path,
|
path = "/swagger" as Path,
|
||||||
exclude = [],
|
exclude = [],
|
||||||
swaggerOptions = {},
|
swaggerOptions = {},
|
||||||
theme = `https://unpkg.com/swagger-ui-dist@${version}/swagger-ui.css`,
|
theme = `https://unpkg.com/swagger-ui-dist@${version}/swagger-ui.css`,
|
||||||
autoDarkMode = true,
|
autoDarkMode = true,
|
||||||
excludeMethods = ['OPTIONS'],
|
excludeMethods = ["OPTIONS"],
|
||||||
excludeTags = []
|
excludeTags = [],
|
||||||
}: ElysiaSwaggerConfig<Path> = {
|
}: ElysiaSwaggerConfig<Path> = {
|
||||||
provider: 'scalar',
|
provider: "scalar",
|
||||||
scalarVersion: 'latest',
|
scalarVersion: "latest",
|
||||||
scalarCDN: '',
|
scalarCDN: "",
|
||||||
scalarConfig: {},
|
scalarConfig: {},
|
||||||
documentation: {},
|
documentation: {},
|
||||||
version: '5.9.0',
|
version: "5.9.0",
|
||||||
excludeStaticFile: true,
|
excludeStaticFile: true,
|
||||||
path: '/swagger' as Path,
|
path: "/swagger" as Path,
|
||||||
exclude: [],
|
exclude: [],
|
||||||
swaggerOptions: {},
|
swaggerOptions: {},
|
||||||
autoDarkMode: true,
|
autoDarkMode: true,
|
||||||
excludeMethods: ['OPTIONS'],
|
excludeMethods: ["OPTIONS"],
|
||||||
excludeTags: []
|
excludeTags: [],
|
||||||
}
|
},
|
||||||
) =>
|
) => {
|
||||||
(app: Elysia) => {
|
const schema = {};
|
||||||
const schema = {}
|
let totalRoutes = 0;
|
||||||
let totalRoutes = 0
|
|
||||||
|
|
||||||
if (!version)
|
if (!version)
|
||||||
version = `https://unpkg.com/swagger-ui-dist@${version}/swagger-ui.css`
|
version = `https://unpkg.com/swagger-ui-dist@${version}/swagger-ui.css`;
|
||||||
|
|
||||||
const info = {
|
const info = {
|
||||||
title: 'Elysia Documentation',
|
title: "Elysia Documentation",
|
||||||
description: 'Development documentation',
|
description: "Development documentation",
|
||||||
version: '0.0.0',
|
version: "0.0.0",
|
||||||
...documentation.info
|
...documentation.info,
|
||||||
}
|
};
|
||||||
|
|
||||||
const relativePath = path.startsWith('/') ? path.slice(1) : path
|
const relativePath = path.startsWith("/") ? path.slice(1) : path;
|
||||||
|
|
||||||
app.get(
|
const app = new Elysia({ name: "@elysiajs/swagger" });
|
||||||
path,
|
|
||||||
() => {
|
app.get(path, function documentation() {
|
||||||
const combinedSwaggerOptions = {
|
const combinedSwaggerOptions = {
|
||||||
url: `${relativePath}/json`,
|
url: `${relativePath}/json`,
|
||||||
dom_id: '#swagger-ui',
|
dom_id: "#swagger-ui",
|
||||||
...swaggerOptions
|
...swaggerOptions,
|
||||||
}
|
};
|
||||||
|
|
||||||
const stringifiedSwaggerOptions = JSON.stringify(
|
const stringifiedSwaggerOptions = JSON.stringify(
|
||||||
combinedSwaggerOptions,
|
combinedSwaggerOptions,
|
||||||
(key, value) => {
|
(key, value) => {
|
||||||
if (typeof value == 'function') return undefined
|
if (typeof value == "function") return undefined;
|
||||||
|
|
||||||
return value
|
return value;
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
|
|
||||||
const scalarConfiguration: ReferenceConfiguration = {
|
const scalarConfiguration: ReferenceConfiguration = {
|
||||||
spec: {
|
spec: {
|
||||||
...scalarConfig.spec,
|
...scalarConfig.spec,
|
||||||
url: `${relativePath}/json`,
|
url: `${relativePath}/json`,
|
||||||
},
|
},
|
||||||
...scalarConfig
|
...scalarConfig,
|
||||||
}
|
};
|
||||||
|
|
||||||
return new Response(
|
return new Response(
|
||||||
provider === 'swagger-ui'
|
provider === "swagger-ui"
|
||||||
? SwaggerUIRender(
|
? SwaggerUIRender(
|
||||||
info,
|
info,
|
||||||
version,
|
version,
|
||||||
theme,
|
theme,
|
||||||
stringifiedSwaggerOptions,
|
stringifiedSwaggerOptions,
|
||||||
autoDarkMode
|
autoDarkMode,
|
||||||
)
|
)
|
||||||
: ScalarRender(
|
: ScalarRender(scalarVersion, scalarConfiguration, scalarCDN),
|
||||||
scalarVersion,
|
|
||||||
scalarConfiguration,
|
|
||||||
scalarCDN
|
|
||||||
),
|
|
||||||
{
|
{
|
||||||
headers: {
|
headers: {
|
||||||
'content-type': 'text/html; charset=utf8'
|
"content-type": "text/html; charset=utf8",
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
)
|
);
|
||||||
}
|
}).get(path === "/" ? "/json" : `${path}/json`, function openAPISchema() {
|
||||||
).get(
|
// @ts-expect-error Private property
|
||||||
path === '/' ? '/json' : `${path}/json`,
|
const routes = app.getGlobalRoutes() as InternalRoute[];
|
||||||
() => {
|
|
||||||
const routes = app.routes as InternalRoute[]
|
|
||||||
|
|
||||||
if (routes.length !== totalRoutes) {
|
if (routes.length !== totalRoutes) {
|
||||||
totalRoutes = routes.length
|
totalRoutes = routes.length;
|
||||||
|
|
||||||
routes.forEach((route: InternalRoute) => {
|
routes.forEach((route: InternalRoute) => {
|
||||||
if (excludeMethods.includes(route.method)) return
|
if (excludeMethods.includes(route.method)) return;
|
||||||
|
|
||||||
registerSchemaPath({
|
registerSchemaPath({
|
||||||
schema,
|
schema,
|
||||||
@@ -129,43 +121,45 @@ export const swagger =
|
|||||||
path: route.path,
|
path: route.path,
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
models: app.definitions?.type,
|
models: app.definitions?.type,
|
||||||
contentType: route.hooks.type
|
contentType: route.hooks.type,
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
openapi: '3.0.3',
|
openapi: "3.0.3",
|
||||||
...{
|
...{
|
||||||
...documentation,
|
...documentation,
|
||||||
tags: documentation.tags?.filter((tag) => !excludeTags?.includes(tag?.name)),
|
tags: documentation.tags?.filter(
|
||||||
|
(tag) => !excludeTags?.includes(tag?.name),
|
||||||
|
),
|
||||||
info: {
|
info: {
|
||||||
title: 'Elysia Documentation',
|
title: "Elysia Documentation",
|
||||||
description: 'Development documentation',
|
description: "Development documentation",
|
||||||
version: '0.0.0',
|
version: "0.0.0",
|
||||||
...documentation.info
|
...documentation.info,
|
||||||
}
|
|
||||||
},
|
},
|
||||||
paths: {...filterPaths(schema, {
|
},
|
||||||
|
paths: {
|
||||||
|
...filterPaths(schema, {
|
||||||
excludeStaticFile,
|
excludeStaticFile,
|
||||||
exclude: Array.isArray(exclude) ? exclude : [exclude]
|
exclude: Array.isArray(exclude) ? exclude : [exclude],
|
||||||
}),
|
}),
|
||||||
...documentation.paths
|
...documentation.paths,
|
||||||
},
|
},
|
||||||
components: {
|
components: {
|
||||||
...documentation.components,
|
...documentation.components,
|
||||||
schemas: {
|
schemas: {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
...app.definitions?.type,
|
...app.definitions?.type,
|
||||||
...documentation.components?.schemas
|
...documentation.components?.schemas,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
} satisfies OpenAPIV3.Document
|
} satisfies OpenAPIV3.Document;
|
||||||
}
|
});
|
||||||
)
|
|
||||||
|
|
||||||
// This is intentional to prevent deeply nested type
|
// This is intentional to prevent deeply nested type
|
||||||
return app
|
return app;
|
||||||
}
|
};
|
||||||
|
|
||||||
export default swagger
|
export default swagger;
|
||||||
|
|||||||
20
src/utils.ts
20
src/utils.ts
@@ -10,7 +10,15 @@ import deepClone from 'lodash.clonedeep'
|
|||||||
export const toOpenAPIPath = (path: string) =>
|
export const toOpenAPIPath = (path: string) =>
|
||||||
path
|
path
|
||||||
.split('/')
|
.split('/')
|
||||||
.map((x) => (x.startsWith(':') ? `{${x.slice(1, x.length)}}` : x))
|
.map((x) => {
|
||||||
|
if (x.startsWith(':')) {
|
||||||
|
x = x.slice(1, x.length)
|
||||||
|
if (x.endsWith('?')) x = x.slice(0, -1)
|
||||||
|
x = `{${x}}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return x
|
||||||
|
})
|
||||||
.join('/')
|
.join('/')
|
||||||
|
|
||||||
export const mapProperties = (
|
export const mapProperties = (
|
||||||
@@ -25,10 +33,16 @@ export const mapProperties = (
|
|||||||
else throw new Error(`Can't find model ${schema}`)
|
else throw new Error(`Can't find model ${schema}`)
|
||||||
|
|
||||||
return Object.entries(schema?.properties ?? []).map(([key, value]) => {
|
return Object.entries(schema?.properties ?? []).map(([key, value]) => {
|
||||||
const { type: valueType = undefined, description, examples, ...schemaKeywords } = value as any
|
const {
|
||||||
|
type: valueType = undefined,
|
||||||
|
description,
|
||||||
|
examples,
|
||||||
|
...schemaKeywords
|
||||||
|
} = value as any
|
||||||
return {
|
return {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
description, examples,
|
description,
|
||||||
|
examples,
|
||||||
schema: { type: valueType, ...schemaKeywords },
|
schema: { type: valueType, ...schemaKeywords },
|
||||||
in: name,
|
in: name,
|
||||||
name: key,
|
name: key,
|
||||||
|
|||||||
@@ -11,12 +11,17 @@ describe('Swagger', () => {
|
|||||||
it('show Swagger page', async () => {
|
it('show Swagger page', async () => {
|
||||||
const app = new Elysia().use(swagger())
|
const app = new Elysia().use(swagger())
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger'))
|
const res = await app.handle(req('/swagger'))
|
||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('returns a valid Swagger/OpenAPI json config', async () => {
|
it('returns a valid Swagger/OpenAPI json config', async () => {
|
||||||
const app = new Elysia().use(swagger())
|
const app = new Elysia().use(swagger())
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger/json')).then((x) => x.json())
|
const res = await app.handle(req('/swagger/json')).then((x) => x.json())
|
||||||
expect(res.openapi).toBe('3.0.3')
|
expect(res.openapi).toBe('3.0.3')
|
||||||
await SwaggerParser.validate(res).catch((err) => fail(err))
|
await SwaggerParser.validate(res).catch((err) => fail(err))
|
||||||
@@ -30,6 +35,8 @@ describe('Swagger', () => {
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger')).then((x) => x.text())
|
const res = await app.handle(req('/swagger')).then((x) => x.text())
|
||||||
expect(
|
expect(
|
||||||
res.includes(
|
res.includes(
|
||||||
@@ -53,6 +60,8 @@ describe('Swagger', () => {
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger')).then((x) => x.text())
|
const res = await app.handle(req('/swagger')).then((x) => x.text())
|
||||||
|
|
||||||
expect(res.includes('<title>Elysia Documentation</title>')).toBe(true)
|
expect(res.includes('<title>Elysia Documentation</title>')).toBe(true)
|
||||||
@@ -73,6 +82,8 @@ describe('Swagger', () => {
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/v2/swagger'))
|
const res = await app.handle(req('/v2/swagger'))
|
||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
|
|
||||||
@@ -89,6 +100,9 @@ describe('Swagger', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger')).then((x) => x.text())
|
const res = await app.handle(req('/swagger')).then((x) => x.text())
|
||||||
const expected = `"persistAuthorization":true`
|
const expected = `"persistAuthorization":true`
|
||||||
|
|
||||||
@@ -104,6 +118,8 @@ describe('Swagger', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger/json'))
|
const res = await app.handle(req('/swagger/json'))
|
||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
const response = await res.json()
|
const response = await res.json()
|
||||||
@@ -126,6 +142,8 @@ describe('Swagger', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger/json'))
|
const res = await app.handle(req('/swagger/json'))
|
||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
const response = await res.json()
|
const response = await res.json()
|
||||||
@@ -146,6 +164,8 @@ describe('Swagger', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger/json'))
|
const res = await app.handle(req('/swagger/json'))
|
||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
const response = await res.json()
|
const response = await res.json()
|
||||||
@@ -157,15 +177,27 @@ describe('Swagger', () => {
|
|||||||
).toBeUndefined()
|
).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
it("should set the required field to true when a request body is present", async () => {
|
it('should set the required field to true when a request body is present', async () => {
|
||||||
const app = new Elysia().use(swagger()).post("/post", () => {}, {
|
const app = new Elysia().use(swagger()).post('/post', () => {}, {
|
||||||
body: t.Object({ name: t.String() }),
|
body: t.Object({ name: t.String() })
|
||||||
});
|
|
||||||
|
|
||||||
const res = await app.handle(req("/swagger/json"));
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
const response = await res.json();
|
|
||||||
expect(response.paths['/post'].post.requestBody.required).toBe(true);
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
|
const res = await app.handle(req('/swagger/json'))
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const response = await res.json()
|
||||||
|
expect(response.paths['/post'].post.requestBody.required).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resolve optional param to param', async () => {
|
||||||
|
const app = new Elysia().use(swagger()).get('/id/:id?', () => {})
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
|
const res = await app.handle(req('/swagger/json'))
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const response = await res.json()
|
||||||
|
expect(response.paths).toContainKey('/id/{id}')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -78,6 +78,8 @@ it('returns a valid Swagger/OpenAPI json config for many routes', async () => {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await app.modules
|
||||||
|
|
||||||
const res = await app.handle(req('/swagger/json')).then((x) => x.json())
|
const res = await app.handle(req('/swagger/json')).then((x) => x.json())
|
||||||
await SwaggerParser.validate(res).catch((err) => fail(err))
|
await SwaggerParser.validate(res).catch((err) => fail(err))
|
||||||
})
|
})
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
|
||||||
|
|
||||||
/* Projects */
|
|
||||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
|
||||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
||||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
|
||||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
|
||||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
||||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
||||||
|
|
||||||
/* Language and Environment */
|
|
||||||
"target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
|
||||||
"lib": ["ESNext", "DOM", "ScriptHost"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
||||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
|
||||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
|
||||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
|
||||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
|
||||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
||||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
||||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
||||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
||||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
||||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
||||||
|
|
||||||
/* Modules */
|
|
||||||
"module": "CommonJS", /* Specify what module code is generated. */
|
|
||||||
// "rootDir": "./src", /* Specify the root folder within your source files. */
|
|
||||||
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
|
||||||
"baseUrl": "./src", /* Specify the base directory to resolve non-relative module names. */
|
|
||||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
||||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
||||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
||||||
"types": ["bun-types"], /* Specify type package names to be included without being referenced in a source file. */
|
|
||||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
||||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
||||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
|
||||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
||||||
|
|
||||||
/* JavaScript Support */
|
|
||||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
||||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
||||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
||||||
|
|
||||||
/* Emit */
|
|
||||||
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
|
||||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
||||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
||||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
||||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
||||||
"outDir": "./dist/cjs", /* Specify an output folder for all emitted files. */
|
|
||||||
// "removeComments": true, /* Disable emitting comments. */
|
|
||||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
|
||||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
||||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
|
||||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
||||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
||||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
||||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
||||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
||||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
||||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
||||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
||||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
||||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
||||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
||||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
||||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
|
||||||
|
|
||||||
/* Interop Constraints */
|
|
||||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
||||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
||||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
|
||||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
||||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
|
||||||
|
|
||||||
/* Type Checking */
|
|
||||||
"strict": true, /* Enable all strict type-checking options. */
|
|
||||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
||||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
||||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
||||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
||||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
||||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
||||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
||||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
||||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
||||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
||||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
||||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
||||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
||||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
|
||||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
||||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
||||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
||||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
||||||
|
|
||||||
/* Completeness */
|
|
||||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
||||||
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
|
|
||||||
},
|
|
||||||
"include": ["src/**/*"]
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
|
"preserveSymlinks": true,
|
||||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||||
|
|
||||||
/* Projects */
|
/* Projects */
|
||||||
@@ -12,7 +13,7 @@
|
|||||||
|
|
||||||
/* Language and Environment */
|
/* Language and Environment */
|
||||||
"target": "ES2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
"target": "ES2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
"lib": ["ESNext", "DOM", "ScriptHost"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
"lib": ["ESNext"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
@@ -26,16 +27,16 @@
|
|||||||
|
|
||||||
/* Modules */
|
/* Modules */
|
||||||
"module": "ES2022", /* Specify what module code is generated. */
|
"module": "ES2022", /* Specify what module code is generated. */
|
||||||
// "rootDir": "./src", /* Specify the root folder within your source files. */
|
"rootDir": "./src", /* Specify the root folder within your source files. */
|
||||||
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
"baseUrl": "./src", /* Specify the base directory to resolve non-relative module names. */
|
// "baseUrl": "./src", /* Specify the base directory to resolve non-relative module names. */
|
||||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
"types": ["bun-types"], /* Specify type package names to be included without being referenced in a source file. */
|
// "types": ["bun-types"], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
"resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
/* JavaScript Support */
|
/* JavaScript Support */
|
||||||
@@ -46,7 +47,7 @@
|
|||||||
/* Emit */
|
/* Emit */
|
||||||
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
"emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
||||||
@@ -70,7 +71,7 @@
|
|||||||
|
|
||||||
/* Interop Constraints */
|
/* Interop Constraints */
|
||||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||||
@@ -100,5 +101,6 @@
|
|||||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
|
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"]
|
"exclude": ["node_modules", "test", "example", "dist", "build.ts"]
|
||||||
|
// "include": ["src/**/*"]
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user