Skip to content

Instantly share code, notes, and snippets.

@bjesuiter
Last active June 9, 2023 08:11
Show Gist options
  • Save bjesuiter/6dce84dcbb5b2867ca6316380c114467 to your computer and use it in GitHub Desktop.
Save bjesuiter/6dce84dcbb5b2867ca6316380c114467 to your computer and use it in GitHub Desktop.
Zod Snippets
// Use this official regex: ^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$
// See here: https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
const regex =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
const SemVer = z.string().regex(regex);
import { z } from 'zod';
/**
* Allows values:
* - undefined
* - null
*
* Transforms incomming null values to undefined, to not have to deal with undefined | null values in code
*/
export function guardNullOrUndefined<T extends z.ZodTypeAny>(schema: T) {
return z
.nullable(z.optional(schema))
.transform((value) => (value === null ? undefined : value));
}
z
.string()
.pipe(
z.preprocess((json) => JSON.parse(String(json)), clientKontextSchema)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment