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

fix: Wrongful generation of Date type #182

Open
wants to merge 2 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
39 changes: 35 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export const mapProperties = (
if (typeof schema === 'string')
if (schema in models) schema = models[schema]
else throw new Error(`Can't find model ${schema}`)

return Object.entries(schema?.properties ?? []).map(([key, value]) => {
const {
type: valueType = undefined,
Expand Down Expand Up @@ -70,15 +69,14 @@ const mapTypesResponse = (
const responses: Record<string, OpenAPIV3.MediaTypeObject> = {}

for (const type of types) {
// console.log(schema)

responses[type] = {
schema:
schema: cleanDateType(
typeof schema === 'string'
? {
$ref: `#/components/schemas/${schema}`
}
: { ...(schema as any) }
)
}
}

Expand Down Expand Up @@ -108,6 +106,7 @@ const cloneHook = <T>(hook: T) => {
if (!hook) return
if (typeof hook === 'string') return hook
if (Array.isArray(hook)) return [...hook]

return { ...hook }
}

Expand Down Expand Up @@ -372,3 +371,35 @@ export const filterPaths = (

return newPaths
}

const cleanDateType = (schema: any): any => {
if (!schema) return schema

if (schema.anyOf && schema.anyOf.some((x: any) => x.type === 'Date')) {
return {
...schema,
anyOf: schema.anyOf.filter((x: any) => x.type !== 'Date')
}
}

if (schema.type === 'object' && schema.properties) {
return {
...schema,
properties: Object.fromEntries(
Object.entries(schema.properties).map(([key, value]) => [
key,
cleanDateType(value)
])
)
}
}

if (schema.type === 'array' && schema.items) {
return {
...schema,
items: cleanDateType(schema.items)
}
}

return schema
}
82 changes: 70 additions & 12 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,27 +232,27 @@ describe('Swagger', () => {
})

it('should hide routes with hide = true from paths', async () => {
const app = new Elysia().use(swagger())
.get("/public", "omg")
const app = new Elysia()
.use(swagger())
.get('/public', 'omg')
.guard({
detail: {
hide: true
}
})
.get("/hidden", "ok")
.get('/hidden', 'ok')

await app.modules

const res = await app.handle(req('/swagger/json'))
expect(res.status).toBe(200)
const response = await res.json()
expect(response.paths['/public']).not.toBeUndefined();
expect(response.paths['/hidden']).toBeUndefined();
expect(response.paths['/public']).not.toBeUndefined()
expect(response.paths['/hidden']).toBeUndefined()
})

it('should expand .all routes', async () => {
const app = new Elysia().use(swagger())
.all("/all", "woah")
const app = new Elysia().use(swagger()).all('/all', 'woah')

await app.modules

Expand All @@ -263,17 +263,75 @@ describe('Swagger', () => {
})

it('should hide routes that are invalid', async () => {
const app = new Elysia().use(swagger())
.get("/valid", "ok")
.route("LOCK", "/invalid", "nope")
const app = new Elysia()
.use(swagger())
.get('/valid', 'ok')
.route('LOCK', '/invalid', 'nope')

await app.modules

const res = await app.handle(req('/swagger/json'))
expect(res.status).toBe(200)
const response = await res.json()
expect(response.paths['/valid']).not.toBeUndefined()
expect(response.paths['/invalid']).toBeUndefined()
})

it('should properly format date-time fields in schema', async () => {
const app = new Elysia().use(swagger()).post('/user', () => {}, {
body: t.Object({
name: t.String(),
createdAt: t.Date(),
metadata: t.Object({
updatedAt: t.Date()
}),
history: t.Array(
t.Object({
timestamp: t.Date()
})
)
})
})

await app.modules

const res = await app.handle(req('/swagger/json'))
expect(res.status).toBe(200)
const response = await res.json()
expect(response.paths['/valid']).not.toBeUndefined();
expect(response.paths['/invalid']).toBeUndefined();

const expectedDateFormat = {
anyOf: [
{
format: 'date',
type: 'string',
default: expect.any(String)
},
{
format: 'date-time',
type: 'string',
default: expect.any(String)
},
{
type: 'number'
}
]
}

// Check root level date
expect(
response.paths['/user'].post.requestBody.content['application/json']
.schema.properties.createdAt
).toMatchObject(expectedDateFormat)

// Check nested date in object
expect(
response.paths['/user'].post.requestBody.content['application/json']
.schema.properties.metadata.properties.updatedAt
).toMatchObject(expectedDateFormat)
// Check date in array items
expect(
response.paths['/user'].post.requestBody.content['application/json']
.schema.properties.history.items.properties.timestamp
).toMatchObject(expectedDateFormat)
})
})