Skip to content

Commit 084d7d5

Browse files
committed
feat: Serialize Date
1 parent b6cdb26 commit 084d7d5

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

src/lib/date.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
interface DateLike {
2+
toISOString: () => string
3+
}
4+
5+
export const isDateLike = (v: unknown): v is DateLike => {
6+
if (v == null) return false
7+
if (typeof v !== 'object') return false
8+
if (
9+
v instanceof Date ||
10+
Object.prototype.toString.call(v) === '[object Date]'
11+
) {
12+
return 'toISOString' in v
13+
}
14+
return false
15+
}

src/lib/serialize.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isDateLike } from './date.js'
2+
13
type Params = Record<string, unknown>
24

35
export const serializeUrlSearchParams = (params: Params): string => {
@@ -38,6 +40,7 @@ const serialize = (k: string, v: unknown): string => {
3840
if (typeof v === 'number') return v.toString()
3941
if (typeof v === 'bigint') return v.toString()
4042
if (typeof v === 'boolean') return v.toString()
43+
if (isDateLike(v)) return v.toISOString()
4144
throw new UnserializableParamError(k, `is a ${typeof v}`)
4245
}
4346

test/serialization.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ test('cannot serialize single element array params with empty string', (t) => {
7575
})
7676
})
7777

78+
test('serializes Date', (t) => {
79+
t.is(
80+
serializeUrlSearchParams({ foo: 1, now: new Date(1740422679000) }),
81+
'foo=1&now=2025-02-24T18%3A44%3A39.000Z',
82+
)
83+
})
84+
7885
test('cannot serialize unserializable values', (t) => {
7986
t.throws(() => serializeUrlSearchParams({ foo: {} }), {
8087
instanceOf: UnserializableParamError,

0 commit comments

Comments
 (0)