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: Correctly set t.Date() defaults #1062

Merged
merged 2 commits into from
Feb 16, 2025
Merged
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
10 changes: 6 additions & 4 deletions src/type-system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,21 +393,23 @@ export const ElysiaType = {
},
Date: (property?: DateOptions) => {
const schema = Type.Date(property)

const _default = property?.default ?
new Date(property.default) : // in case the default is an ISO string or milliseconds from epoch
undefined;
return t
.Transform(
t.Union(
[
Type.Date(property),
t.String({
format: 'date',
default: new Date().toISOString()
default: _default?.toISOString()
}),
t.String({
format: 'date-time',
default: new Date().toISOString()
default: _default?.toISOString()
}),
t.Number()
t.Number({ default: _default?.getTime() })
],
property
)
Expand Down
23 changes: 22 additions & 1 deletion test/type-system/date.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,35 @@
import Elysia, { t } from '../../src'
import { describe, expect, it } from 'bun:test'
import { Value } from '@sinclair/typebox/value'
import { TBoolean, TDate, TypeBoxError } from '@sinclair/typebox'
import { TBoolean, TDate, TUnion, TypeBoxError } from '@sinclair/typebox'
import { post } from '../utils'

describe('TypeSystem - Date', () => {
it('Create', () => {
expect(Value.Create(t.Date())).toBeInstanceOf(Date)
})

it('No default date provided', () => {
const schema = t.Date()
expect(schema.default).toBeUndefined();

const unionSchema = schema as unknown as TUnion
for (const type of unionSchema.anyOf) {
expect(type.default).toBeUndefined();
}
})

it('Default date provided', () => {
const given = new Date("2025-01-01T00:00:00.000Z")
const schema = t.Date({ default: given })
expect(schema.default).toEqual(given);

const unionSchema = schema as unknown as TUnion
for (const type of unionSchema.anyOf) {
expect(new Date(type.default)).toEqual(given);
}
})

it('Check', () => {
const schema = t.Date()

Expand Down