Skip to content

Commit

Permalink
Support Date and Temporal.Instant (#6)
Browse files Browse the repository at this point in the history
* feat: Serialize Date

* feat: Serialize Temporal.Instant

* docs: Add serialization strategy

* docs: Move Motivation down in README

* Fix typo
  • Loading branch information
razor-x authored Feb 24, 2025
2 parents b6cdb26 + c0300dc commit 619b45f
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 28 deletions.
82 changes: 54 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,31 @@ See this test for the [serialization behavior](./test/serialization.test.ts).

[URLSearchParams]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

## Motivation

URL search parameters are strings, however the Seam API will parse parameters as complex types.
The Seam SDK must accept the complex types as input and serialize these
to search parameters in a way supported by the Seam API.

There is no single standard for this serialization.
This module establishes the serialization standard adopted by the Seam API.

### Why not use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)?

- Passing a raw object to URLSearchParams has unpredictable serialization behavior.

### Why not [qs](https://github.com/ljharb/qs)?

- Not a zero-dependency module. Has quite a few dependency layers.
- Impractile as a reference implementation.
qs enables complex, non-standard parsing and serialization,
which makes ensuing SDK parity much harder.
Similarly, this puts an unreasonable burden on user's of the HTTP API or those implementing their own client.
- The Seam API must ensure it handles a well defined set of non-string query parameters consistency.
Using qs would allow the SDK to send unsupported or incorrectly serialized parameter types to the API
resulting in unexpected behavior.

### Why not use the default [Axios](https://axios-http.com/) serializer?

- Using the default [Axios] serializer was the original approach,
however it had similar issues to using URLSearchParams and qs as noted above.
### Serialization strategy

Serialization uses
[`URLSearchParams.toString()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/toString#return_value)
which encodes most non-alphanumeric characters.

- The primitive types `string`, `number`, and `bigint` are serialized using `.toString()`.
- The primitive `boolean` type is serialized using `.toString()` to `'true'` or `'false'`.
- The primitive `null` and `undefined` values are removed,
e.g., `{ foo: null, bar: undefined, baz: 1 }` serializes to `baz=1`.
- `Date` objects are detected and serialized using `Date.toISOString()`.
- `Temporal.Instant` objects are detected and serialized by first converting them to `Date`
and then serializing the `Date` as above.
- Arrays are serialized using
[`URLSearchParams.append()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/append):
- Array values are serialized as above.
- The array `{ foo: [1, 2] }` serializes to `foo=1&foo=2`.
- The single element array `{ foo: [1] }` serializes to `foo=1`.
- The empty array `{ foo: [] }` serializes to `foo=`.
- Serialization of the single element array containing the empty string is not supported
and will throw an `UnserializableParamError`.
Otherwise, the serialization of `{ foo: [''] }` would conflict with `{ foo: [] }`.
This serializer chooses to support the more common and more useful case of an empty array.
- Serialization of functions or other objects is not supported
and will throw an `UnserializableParamError`.

## Installation

Expand Down Expand Up @@ -111,6 +108,35 @@ const { data } = await client.get('/search', {

[Axios]: https://axios-http.com/

## Motivation

URL search parameters are strings, however the Seam API will parse parameters as complex types.
The Seam SDK must accept the complex types as input and serialize these
to search parameters in a way supported by the Seam API.

There is no single standard for this serialization.
This module establishes the serialization standard adopted by the Seam API.

### Why not use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)?

- Passing a raw object to URLSearchParams has unpredictable serialization behavior.

### Why not [qs](https://github.com/ljharb/qs)?

- Not a zero-dependency module. Has quite a few dependency layers.
- Impractical as a reference implementation.
qs enables complex, non-standard parsing and serialization,
which makes ensuing SDK parity much harder.
Similarly, this puts an unreasonable burden on user's of the HTTP API or those implementing their own client.
- The Seam API must ensure it handles a well defined set of non-string query parameters consistency.
Using qs would allow the SDK to send unsupported or incorrectly serialized parameter types to the API
resulting in unexpected behavior.

### Why not use the default [Axios](https://axios-http.com/) serializer?

- Using the default [Axios] serializer was the original approach,
however it had similar issues to using URLSearchParams and qs as noted above.

## Development and Testing

### Quickstart
Expand Down
29 changes: 29 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"npm": ">= 9.0.0"
},
"devDependencies": {
"@js-temporal/polyfill": "^0.4.4",
"@types/node": "^20.8.10",
"ava": "^6.0.1",
"axios": "^1.6.5",
Expand Down
32 changes: 32 additions & 0 deletions src/lib/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
interface DateLike {
toISOString: () => string
}

export const isDateLike = (v: unknown): v is DateLike => {
if (v == null) return false
if (typeof v !== 'object') return false
if (
v instanceof Date ||
Object.prototype.toString.call(v) === '[object Date]'
) {
return 'toISOString' in v
}
return false
}

interface TemporalInstantLike {
epochMilliseconds: number
}

export const isTemporalInstantLike = (v: unknown): v is TemporalInstantLike => {
if (v == null) return false
if (typeof v !== 'object') return false
if (!('epochMilliseconds' in v)) return false
try {
if (typeof v.epochMilliseconds !== 'number') return false
if (isNaN(v.epochMilliseconds)) return false
return true
} catch {
return false
}
}
6 changes: 6 additions & 0 deletions src/lib/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isDateLike, isTemporalInstantLike } from './date.js'

type Params = Record<string, unknown>

export const serializeUrlSearchParams = (params: Params): string => {
Expand Down Expand Up @@ -38,6 +40,10 @@ const serialize = (k: string, v: unknown): string => {
if (typeof v === 'number') return v.toString()
if (typeof v === 'bigint') return v.toString()
if (typeof v === 'boolean') return v.toString()
if (isDateLike(v)) return v.toISOString()
if (isTemporalInstantLike(v)) {
return new Date(v.epochMilliseconds).toISOString()
}
throw new UnserializableParamError(k, `is a ${typeof v}`)
}

Expand Down
19 changes: 19 additions & 0 deletions test/serialization.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Temporal } from '@js-temporal/polyfill'
import test from 'ava'

import {
Expand Down Expand Up @@ -75,6 +76,24 @@ test('cannot serialize single element array params with empty string', (t) => {
})
})

test('serializes Date', (t) => {
t.is(
serializeUrlSearchParams({ foo: 1, now: new Date(1740422679000) }),
'foo=1&now=2025-02-24T18%3A44%3A39.000Z',
)
})

test.only('serializes Temporal.Instant', (t) => {
t.is(
serializeUrlSearchParams({
foo: 1,
now: Temporal.Instant.fromEpochMilliseconds(1740422679000),
}),

'foo=1&now=2025-02-24T18%3A44%3A39.000Z',
)
})

test('cannot serialize unserializable values', (t) => {
t.throws(() => serializeUrlSearchParams({ foo: {} }), {
instanceOf: UnserializableParamError,
Expand Down

0 comments on commit 619b45f

Please sign in to comment.