Skip to content

Commit 4527d8b

Browse files
committed
feat: Serialize null
BREAKING CHANGE: The primitive value null will now be serialized instead of removed, e.g., { foo: null } will now be serialized to 'foo='.
1 parent 01706d3 commit 4527d8b

File tree

3 files changed

+12
-7
lines changed

3 files changed

+12
-7
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,10 @@ the consumer parsing the string, it can be unambigously parsed back to the origi
2929
- The primitive `number` and `bigint` types are serialized using `.toString()`.
3030
- The primitive `boolean` type is serialized using `.toString()`,
3131
e.g., `{ foo: true, bar: false }` serializes to `foo=true&bar=false`.
32-
- The primitive `null` and `undefined` values are removed,
33-
e.g., `{ foo: null, bar: undefined, baz: 1 }` serializes to `baz=1`.
32+
- The primitive `null` is serialized to an empty value,
33+
e.g., `{ foo: null }` serializes to `foo=`.
34+
- and `undefined` values are removed,
35+
e.g., `{ foo: undefined, bar: 1 }` serializes to `baz=1`.
3436
- `Date` objects are detected and serialized using `Date.toISOString()`,
3537
e.g., `{ foo: new Date(0) }` serializes to `foo=1970-01-01T00%3A00%3A00.000Z`.
3638
- `Temporal.Instant` objects are detected and serialized by first converting them to `Date`

src/lib/serialize.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ const nestedUpdateUrlSearchParams = (
3131

3232
const name = currentPath.join('.')
3333

34-
if (value == null) continue
34+
if (value == null) {
35+
if (value === null) searchParams.set(name, '')
36+
continue
37+
}
3538

3639
if (Array.isArray(value)) {
3740
if (value.length === 0) searchParams.set(name, '')

test/serialization.test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ test('removes undefined params', (t) => {
3232
t.is(serializeUrlSearchParams({ foo: 1, bar: undefined }), 'foo=1')
3333
})
3434

35-
test('removes null params', (t) => {
36-
t.is(serializeUrlSearchParams({ bar: null }), '')
37-
t.is(serializeUrlSearchParams({ foo: 1, bar: null }), 'foo=1')
35+
test('serializes null params', (t) => {
36+
t.is(serializeUrlSearchParams({ bar: null }), 'bar=')
37+
t.is(serializeUrlSearchParams({ foo: 1, bar: null }), 'bar=&foo=1')
3838
})
3939

4040
test('serializes empty array params', (t) => {
@@ -116,7 +116,7 @@ test('serializes plain objects', (t) => {
116116
foo: 1,
117117
bar: { baz: { x: { z: null } } },
118118
}),
119-
'foo=1',
119+
'bar.baz.x.z=&foo=1',
120120
)
121121

122122
t.is(

0 commit comments

Comments
 (0)