-
Notifications
You must be signed in to change notification settings - Fork 0
Add parseUrlSearchParams #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
razor-x
wants to merge
32
commits into
main
Choose a base branch
from
dev
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 13 commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
f73d27e
Add @seamapi/url-search-params-serializer for testing
razor-x 6261ad0
Add zod for testing
razor-x 2ad9d57
Add parseUrlSearchParams with failing tests
razor-x 11e98ca
ci: Generate code
seambot 3308bc4
Add basic parsing implementation
razor-x 5dfd48e
Add basic coercion
razor-x af489b8
Add suggested strategy with zodSchemaToParamSchema
razor-x 4e39fd8
Add UnparseableSchemaError
razor-x d990492
Implement basic zodSchemaToParamSchema
razor-x 2295f48
Use zodSchemaToParamSchema in parseUrlSearchParams
razor-x ebecd70
Test nesting
razor-x be0f990
Add parsing rules
razor-x 9533aa4
ci: Format code
seambot 45d311a
Add TODO
razor-x 753923d
Update to url-search-params-serializer v2
razor-x 40ffb39
Extend README
razor-x 0783808
Add usage
razor-x 96a4f8a
ci: Format code
seambot 5145615
Update README.md
razor-x 24b9cb5
Use test macro
razor-x d3c0faf
Replace TODO with test.todo
razor-x bd01d41
Add todo tests for generous parsing
razor-x c25f13f
Rename test
razor-x c257cf2
Test whitespace for number
razor-x a07ff78
Parse boolean
razor-x 6f0bec5
Pass though non-numbers
razor-x 1edc1f8
Note truthy and falsy values
razor-x 05da702
ci: Format code
seambot 9a20fcc
Restrict parsing boolean array
razor-x 68f09a3
Add date_array
razor-x f938336
Add record ValueTypes
razor-x c42a12e
Update README.md
razor-x File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import type { Builder, Command, Describe, Handler } from 'landlubber' | ||
import { z } from 'zod' | ||
|
||
import { parseUrlSearchParams } from '@seamapi/url-search-params-parser' | ||
|
||
interface Options { | ||
query: string | ||
} | ||
|
||
export const command: Command = 'parse query' | ||
|
||
export const describe: Describe = 'Parse query' | ||
|
||
export const builder: Builder = { | ||
query: { | ||
type: 'string', | ||
describe: 'Query string', | ||
}, | ||
} | ||
|
||
export const handler: Handler<Options> = async ({ query, logger }) => { | ||
logger.info({ data: parseUrlSearchParams(query, schema) }, 'params') | ||
} | ||
|
||
const schema = z | ||
.object({ | ||
a: z.string(), | ||
b: z.number(), | ||
c: z.boolean(), | ||
d: z.null(), | ||
e: z.array(z.union([z.string(), z.number()])), | ||
f: z.array(z.string()), | ||
g: z.date(), | ||
h: z.date(), | ||
i: z | ||
.object({ | ||
foo: z.number(), | ||
bar: z | ||
.object({ | ||
baz: z.number(), | ||
fizz: z.array(z.union([z.string(), z.number()])), | ||
}) | ||
.optional(), | ||
}) | ||
.optional(), | ||
}) | ||
.optional() |
This file was deleted.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
export { todo } from './todo.js' | ||
export * from './parse.js' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import test from 'ava' | ||
import { z } from 'zod' | ||
|
||
import { parseUrlSearchParams } from './parse.js' | ||
|
||
test('parseUrlSearchParams: with string input', (t) => { | ||
t.deepEqual( | ||
parseUrlSearchParams( | ||
'foo=d&bar=2', | ||
z.object({ foo: z.string().optional(), bar: z.number().optional() }), | ||
), | ||
{ foo: 'd', bar: 2 }, | ||
) | ||
}) | ||
|
||
test('parseUrlSearchParams: with URLSearchParams input', (t) => { | ||
t.deepEqual( | ||
parseUrlSearchParams( | ||
new URLSearchParams('foo=d&bar=2'), | ||
z.object({ foo: z.string().optional(), bar: z.number().optional() }), | ||
), | ||
{ foo: 'd', bar: 2 }, | ||
'with URLSearchParams input', | ||
) | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import type { ZodTypeAny } from 'zod' | ||
|
||
import { | ||
type ParamSchema, | ||
type ValueType, | ||
zodSchemaToParamSchema, | ||
} from './schema.js' | ||
import { isZodObject } from './zod.js' | ||
|
||
export const parseUrlSearchParams = ( | ||
query: URLSearchParams | string, | ||
schema: ZodTypeAny, | ||
): Record<string, unknown> => { | ||
const searchParams = | ||
typeof query === 'string' ? new URLSearchParams(query) : query | ||
|
||
if (!isZodObject(schema)) { | ||
throw new Error( | ||
'The Zod schema to parse URL search params must be an ZodObject schema', | ||
) | ||
} | ||
|
||
const paramSchema = zodSchemaToParamSchema(schema) | ||
return parseFromParamSchema(searchParams, paramSchema, []) as Record< | ||
string, | ||
unknown | ||
> | ||
} | ||
|
||
const parseFromParamSchema = ( | ||
searchParams: URLSearchParams, | ||
node: ParamSchema | ValueType, | ||
path: string[], | ||
): Record<string, unknown> | unknown => { | ||
if (typeof node === 'string') { | ||
// TODO: For array parsing, try to lookup foo=, then foo[]= patterns, | ||
// if only one match, try to detect commas, otherwise ignore commas. | ||
// if both foo= and foo[]= this is a parse error | ||
// more generally, try to find a matching key for this node in the searchParams | ||
// and throw if conflicting keys are found, e.g, both foo= and foo[]= | ||
const key = path.join('.') | ||
return parse(key, searchParams.getAll(key), node) | ||
} | ||
|
||
const entries = Object.entries(node).reduce< | ||
Array<[string, Record<string, unknown> | unknown]> | ||
>((acc, entry) => { | ||
const [k, v] = entry | ||
const currentPath = [...path, k] | ||
return [...acc, [k, parseFromParamSchema(searchParams, v, currentPath)]] | ||
}, []) | ||
|
||
return Object.fromEntries(entries) | ||
} | ||
|
||
const parse = (k: string, values: string[], type: ValueType): unknown => { | ||
// TODO: Add better errors with coercion. If coercion fails, passthough? | ||
// TODO: Is this Number parsing safe? | ||
if (values.length === 0) return undefined | ||
if (type === 'number') return Number(values[0]) | ||
if (type === 'boolean') return values[0] === 'true' | ||
if (type === 'string') return String(values[0]) | ||
if (type === 'string_array') return values | ||
if (type === 'number_array') return values.map((v) => Number(v)) | ||
throw new UnparseableSearchParamError(k, 'unsupported type') | ||
} | ||
|
||
export class UnparseableSearchParamError extends Error { | ||
constructor(name: string, message: string) { | ||
super(`Could not parse parameter: '${name}' ${message}`) | ||
this.name = this.constructor.name | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
import test from 'ava' | ||
import { z } from 'zod' | ||
|
||
import { UnparseableSchemaError, zodSchemaToParamSchema } from './schema.js' | ||
|
||
test('zodSchemaToParamSchema: parses flat object schemas', (t) => { | ||
t.deepEqual(zodSchemaToParamSchema(z.object({ foo: z.string() })), { | ||
foo: 'string', | ||
}) | ||
t.deepEqual( | ||
zodSchemaToParamSchema( | ||
z.object({ | ||
a: z.string(), | ||
b: z.number(), | ||
c: z.boolean(), | ||
d: z.array(z.string()), | ||
}), | ||
), | ||
{ | ||
a: 'string', | ||
b: 'number', | ||
c: 'boolean', | ||
d: 'string_array', | ||
}, | ||
) | ||
}) | ||
|
||
test('zodSchemaToParamSchema: parses nested object schemas', (t) => { | ||
t.deepEqual(zodSchemaToParamSchema(z.object({ foo: z.string() })), { | ||
foo: 'string', | ||
}) | ||
t.deepEqual( | ||
zodSchemaToParamSchema( | ||
z.object({ | ||
a: z.string(), | ||
b: z.object({ | ||
c: z.boolean(), | ||
d: z.array(z.string()), | ||
e: z.object({ | ||
f: z.boolean(), | ||
}), | ||
}), | ||
}), | ||
), | ||
{ | ||
a: 'string', | ||
b: { | ||
c: 'boolean', | ||
d: 'string_array', | ||
e: { | ||
f: 'boolean', | ||
}, | ||
}, | ||
}, | ||
) | ||
}) | ||
|
||
test('zodSchemaToParamSchema: cannot parse non-object schemas', (t) => { | ||
t.throws(() => zodSchemaToParamSchema(z.number()), { | ||
instanceOf: UnparseableSchemaError, | ||
}) | ||
t.throws(() => zodSchemaToParamSchema(z.enum(['foo'])), { | ||
instanceOf: UnparseableSchemaError, | ||
}) | ||
t.throws(() => zodSchemaToParamSchema(z.string()), { | ||
instanceOf: UnparseableSchemaError, | ||
}) | ||
t.throws(() => zodSchemaToParamSchema(z.map(z.string(), z.string())), { | ||
instanceOf: UnparseableSchemaError, | ||
}) | ||
t.throws(() => zodSchemaToParamSchema(z.array(z.string())), { | ||
instanceOf: UnparseableSchemaError, | ||
}) | ||
t.throws(() => zodSchemaToParamSchema(z.null()), { | ||
instanceOf: UnparseableSchemaError, | ||
}) | ||
t.throws(() => zodSchemaToParamSchema(z.union([z.number(), z.string()])), { | ||
instanceOf: UnparseableSchemaError, | ||
}) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@phpnode Let me know if these rules make sense 🙏🏻