Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 11 additions & 1 deletion src/type-system/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Type, Kind } from '@sinclair/typebox'
import { Type, Kind, Static } from '@sinclair/typebox'
import type {
ArrayOptions,
DateOptions,
Expand Down Expand Up @@ -492,12 +492,21 @@ export const ElysiaType = {
})
.Encode((value) => value) as unknown as TUnsafe<File[]>,

/**
* @deprecated Use MaybeNull instead which is OpenAPI 3.0 compliant. Will be removed in the next major release
*/
Nullable: <T extends TSchema>(schema: T, options?: SchemaOptions) =>
t.Union([schema, t.Null()], {
...options,
nullable: true
}),

MaybeNull: <T extends TSchema>(schema: T): TUnsafe<Static<T> | null> =>
Type.Unsafe({
...schema,
nullable: true,
}),

/**
* Allow Optional, Nullable and Undefined
*/
Expand Down Expand Up @@ -660,6 +669,7 @@ t.Files = (arg) => {
}

t.Nullable = ElysiaType.Nullable
t.MaybeNull = ElysiaType.MaybeNull
t.MaybeEmpty = ElysiaType.MaybeEmpty
t.Cookie = ElysiaType.Cookie
t.Date = ElysiaType.Date
Expand Down
53 changes: 53 additions & 0 deletions test/type-system/maybe-null.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'bun:test'
import Elysia, { t } from '../../src'
import { post } from '../utils'

describe('TypeSystem - MaybeNull', () => {
it('OpenAPI compliant', () => {
const schema = t.MaybeNull(t.String());

expect(schema).toMatchObject({
type: "string",
nullable: true
});

const objSchema = t.Object({
name: t.MaybeNull(t.String())
});

expect(objSchema).toMatchObject({
type: "object",
properties: {
name: {
type: "string",
nullable: true
}
},
});
});

it('Validate', async () => {
const app = new Elysia().post('/', ({ body }) => body, {
body: t.Object({
name: t.Nullable(t.String())
})
})

const res1 = await app.handle(
post('/', {
name: '123'
})
)
expect(res1.status).toBe(200)
expect(await res1.json()).toEqual({ name: '123' })

const res2 = await app.handle(post('/', {
name: null
}))
expect(res2.status).toBe(200)
expect(await res2.json()).toEqual({ name: null })

const res3 = await app.handle(post('/', {}))
expect(res3.status).toBe(422)
});
})
Loading