Skip to content

Commit 5dfd48e

Browse files
committed
Add basic coercion
1 parent 3308bc4 commit 5dfd48e

File tree

3 files changed

+7
-6
lines changed

3 files changed

+7
-6
lines changed

src/lib/parse.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ test('parseUrlSearchParams: with string input', (t) => {
99
'foo=d&bar=2',
1010
z.object({ foo: z.string().optional(), bar: z.number().optional() }),
1111
),
12-
{ foo: 'd', bar: '2' },
12+
{ foo: 'd', bar: 2 },
1313
)
1414
})
1515

@@ -19,7 +19,7 @@ test('parseUrlSearchParams: with URLSearchParams input', (t) => {
1919
new URLSearchParams('foo=d&bar=2'),
2020
z.object({ foo: z.string().optional(), bar: z.number().optional() }),
2121
),
22-
{ foo: 'd', bar: '2' },
22+
{ foo: 'd', bar: 2 },
2323
'with URLSearchParams input',
2424
)
2525
})

src/lib/parse.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,10 @@ export const parseUrlSearchParams = (
3535
}
3636

3737
const parse = (k: string, values: string[], schema: ZodTypeAny): unknown => {
38-
if (isZodNumber(schema)) return values[0]
39-
if (isZodBoolean(schema)) return values[0]
40-
if (isZodString(schema)) return values[0]
38+
// TODO: Add better errors with coercion. If coercion fails, passthough?
39+
if (isZodNumber(schema)) return Number(values[0])
40+
if (isZodBoolean(schema)) return values[0] === 'true'
41+
if (isZodString(schema)) return String(values[0])
4142
if (isZodArray(schema)) return values
4243
throw new UnparseableSearchParamError(k, 'unsupported type')
4344
}

test/parse.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { z } from 'zod'
44

55
import { parseUrlSearchParams } from '@seamapi/url-search-params-parser'
66

7-
test('parses empty string', (t) => {
7+
test('parses empty params', (t) => {
88
const schema = z.object({ foo: z.string() })
99
const input = {}
1010
t.deepEqual(

0 commit comments

Comments
 (0)