Skip to content

Standalone Validators support, modelname[] in body fix and globalDefinitions complience fix #219

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

Open
wants to merge 3 commits 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { Elysia, type InternalRoute } from 'elysia'
import { Elysia, TSchema, type InternalRoute } from 'elysia'

import { SwaggerUIRender } from './swagger'
import { ScalarRender } from './scalar'
Expand Down Expand Up @@ -130,7 +130,8 @@ export const swagger = <Path extends string = '/swagger'>({
path: route.path,
// @ts-ignore
models: app.getGlobalDefinitions?.().type,
contentType: route.hooks.type
contentType: route.hooks.type,
standaloneValidators: route.standaloneValidators
})
})
else
Expand All @@ -141,11 +142,21 @@ export const swagger = <Path extends string = '/swagger'>({
path: route.path,
// @ts-ignore
models: app.getGlobalDefinitions?.().type,
contentType: route.hooks.type
contentType: route.hooks.type,
standaloneValidators: route.standaloneValidators
})
})
}

// @ts-ignore
const globalDefinitions = { ...app.getGlobalDefinitions?.().type }
// remove $id from globalDefinitions as it breaks OpenAPI compliance
Object.entries(globalDefinitions).map(([key, value]) => {
if (value.$id) {
delete globalDefinitions[key].$id
}
})

return {
openapi: '3.0.3',
...{
Expand Down
62 changes: 58 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { normalize } from 'pathe'
import { replaceSchemaType, t, type HTTPMethod, type LocalHook } from 'elysia'
import {
InputSchema,
replaceSchemaType,
t,
type HTTPMethod,
type LocalHook
} from 'elysia'

import { Kind, type TSchema } from '@sinclair/typebox'
import type { OpenAPIV3 } from 'openapi-types'
Expand Down Expand Up @@ -128,6 +134,43 @@ export const generateOperationId = (method: string, paths: string) => {
return operationId
}

function resolveModel(
model: TSchema | string | undefined,
models: Record<string, TSchema>
) {
if (typeof model === 'object') return model
// this intentionally doesn't include the 'modelname[]' check
// because it doesn't make sense to merge t.Array using t.Composite
if (typeof model === 'string') return models[model]
return undefined
}

function compositeStandalone(
hook: InputSchema,
validators: InputSchema[] | undefined,
models: Record<string, TSchema>
) {
if (!validators) return hook
if (validators.length === 0) return hook

const mergeProp = (prop: keyof Omit<InputSchema, 'response'>) => {
const array = [hook[prop], ...validators.map((x) => x[prop])]
.map((x) => resolveModel(x, models))
.filter((x) => x !== undefined)
if (array.length === 0) return undefined
if (array.length === 1) return array[0]
return t.Composite(array)
}

return {
...hook,
body: mergeProp('body'),
params: mergeProp('params'),
headers: mergeProp('headers'),
query: mergeProp('query')
}
}

const cloneHook = <T>(hook: T) => {
if (!hook) return
if (typeof hook === 'string') return hook
Expand All @@ -140,16 +183,19 @@ export const registerSchemaPath = ({
path,
method,
hook,
models
models,
standaloneValidators
}: {
schema: Partial<OpenAPIV3.PathsObject>
contentType?: string | string[]
path: string
method: HTTPMethod
hook?: LocalHook<any, any, any, any, any, any>
models: Record<string, TSchema>
standaloneValidators?: InputSchema[]
}) => {
hook = cloneHook(hook)
hook = compositeStandalone(hook, standaloneValidators, models)

if (hook.parse && !Array.isArray(hook.parse)) hook.parse = [hook.parse]

Expand Down Expand Up @@ -216,6 +262,7 @@ export const registerSchemaPath = ({
additionalProperties,
patternProperties,
$ref,
items,
...rest
} = responseSchema as typeof responseSchema & {
type: string
Expand All @@ -234,7 +281,7 @@ export const registerSchemaPath = ({
type,
properties,
patternProperties,
items: responseSchema.items,
items,
required
} as any)
: responseSchema
Expand Down Expand Up @@ -353,7 +400,14 @@ export const registerSchemaPath = ({
required: true,
content: mapTypesResponse(
contentTypes,
typeof bodySchema === 'string'
typeof bodySchema === 'string' && bodySchema.slice(-2) === '[]'
? {
type: 'array',
items: {
$ref: `#/components/schemas/${bodySchema.slice(0, -2)}`
}
}
: typeof bodySchema === 'string'
? {
$ref: `#/components/schemas/${bodySchema}`
}
Expand Down
15 changes: 14 additions & 1 deletion test/validate-schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,28 @@ it('returns a valid Swagger/OpenAPI json config for many routes', async () => {
.get('/unpath/:id', ({ params: { id } }) => id, {
response: t.String({ description: 'sample description' })
})
.model({
thing: t.Object({
bar: t.String()
})
})
.get(
'/unpath/:id/:name/:age',
({ params: { id, name } }) => `${id} ${name}`,
{
type: 'json',
response: t.String({ description: 'sample description' }),
params: t.Object({ id: t.String(), name: t.String() })
params: t.Object({ id: t.String(), name: t.String() }),
body: "thing[]"
}
)
.guard({
schema: "standalone",
body: t.Object({
foo: t.String()
}),
query: "thing"
})
.post(
'/json/:id',
({ body, params: { id }, query: { name, email, birthday } }) => ({
Expand Down