Skip to content

Commit

Permalink
feat: Add validation support (Zod & others)
Browse files Browse the repository at this point in the history
  • Loading branch information
franky47 committed Jan 28, 2024
1 parent c6136a2 commit 8a1f6d7
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion packages/nuqs/src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,27 @@ export type ParserBuilder<T> = Required<Parser<T>> &
*/
withOptions<This, Shallow>(this: This, options: Options<Shallow>): This

/**
* Pass in a validation function to perform runtime checks on the parsed
* value. If the validation fails, the value will be set to `null` (or
* the default value if specified).
*
* Validation must be synchronous, and must throw an error on invalid
* inputs.
*
* Example with Zod:
* ```ts
* const [posInt, setPosInt] = useQueryState(
* 'value',
* parseAsInteger.withValidation(z.number().positive().parse)
* )
* ```
*
* @param this
* @param validate
*/
withValidation<This>(this: This, validate: (input: unknown) => T): This

/**
* Specifying a default value makes the hook state non-nullable when the
* query is missing from the URL.
Expand Down Expand Up @@ -93,6 +114,18 @@ export function createParser<T>(parser: Required<Parser<T>>): ParserBuilder<T> {
return {
...parser,
parseServerSide: parseServerSideNullable,
withValidation(validate) {
return {
...this,
parse: (value: string) => {
const parsed = parser.parse(value)
if (parsed === null) {
return null
}
return validate(parsed)
}
}
},
withDefault(defaultValue) {
return {
...this,
Expand All @@ -102,7 +135,7 @@ export function createParser<T>(parser: Required<Parser<T>>): ParserBuilder<T> {
}
}
},
withOptions(options: Options) {
withOptions(options) {
return {
...this,
...options
Expand Down

0 comments on commit 8a1f6d7

Please sign in to comment.