Last active
June 9, 2023 08:11
-
-
Save bjesuiter/6dce84dcbb5b2867ca6316380c114467 to your computer and use it in GitHub Desktop.
Zod Snippets
This file contains 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
// 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); |
This file contains 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
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)); | |
} |
This file contains 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
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