Skip to content

Commit cf2943f

Browse files
committed
feat: Serialize Temporal.Instant
1 parent 084d7d5 commit cf2943f

File tree

5 files changed

+63
-1
lines changed

5 files changed

+63
-1
lines changed

package-lock.json

Lines changed: 29 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
"npm": ">= 9.0.0"
6969
},
7070
"devDependencies": {
71+
"@js-temporal/polyfill": "^0.4.4",
7172
"@types/node": "^20.8.10",
7273
"ava": "^6.0.1",
7374
"axios": "^1.6.5",

src/lib/date.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,20 @@ export const isDateLike = (v: unknown): v is DateLike => {
1313
}
1414
return false
1515
}
16+
17+
interface TemporalInstantLike {
18+
epochMilliseconds: number
19+
}
20+
21+
export const isTemporalInstantLike = (v: unknown): v is TemporalInstantLike => {
22+
if (v == null) return false
23+
if (typeof v !== 'object') return false
24+
if (!('epochMilliseconds' in v)) return false
25+
try {
26+
if (typeof v.epochMilliseconds !== 'number') return false
27+
if (isNaN(v.epochMilliseconds)) return false
28+
return true
29+
} catch {
30+
return false
31+
}
32+
}

src/lib/serialize.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isDateLike } from './date.js'
1+
import { isDateLike, isTemporalInstantLike } from './date.js'
22

33
type Params = Record<string, unknown>
44

@@ -41,6 +41,9 @@ const serialize = (k: string, v: unknown): string => {
4141
if (typeof v === 'bigint') return v.toString()
4242
if (typeof v === 'boolean') return v.toString()
4343
if (isDateLike(v)) return v.toISOString()
44+
if (isTemporalInstantLike(v)) {
45+
return new Date(v.epochMilliseconds).toISOString()
46+
}
4447
throw new UnserializableParamError(k, `is a ${typeof v}`)
4548
}
4649

test/serialization.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { Temporal } from '@js-temporal/polyfill'
12
import test from 'ava'
23

34
import {
@@ -82,6 +83,17 @@ test('serializes Date', (t) => {
8283
)
8384
})
8485

86+
test.only('serializes Temporal.Instant', (t) => {
87+
t.is(
88+
serializeUrlSearchParams({
89+
foo: 1,
90+
now: Temporal.Instant.fromEpochMilliseconds(1740422679000),
91+
}),
92+
93+
'foo=1&now=2025-02-24T18%3A44%3A39.000Z',
94+
)
95+
})
96+
8597
test('cannot serialize unserializable values', (t) => {
8698
t.throws(() => serializeUrlSearchParams({ foo: {} }), {
8799
instanceOf: UnserializableParamError,

0 commit comments

Comments
 (0)