Skip to content

Instantly share code, notes, and snippets.

@thekarel
Last active November 1, 2024 15:18
Show Gist options
  • Save thekarel/50dae1bfbf1e7ab911c2ab52bfd729eb to your computer and use it in GitHub Desktop.
Save thekarel/50dae1bfbf1e7ab911c2ab52bfd729eb to your computer and use it in GitHub Desktop.
TypeID Valibot Schema
import {fromString, type TypeID} from 'typeid-js'
import * as v from 'valibot'
/**
* Create a Valibot schema for a TypeID with a given prefix
*
* Example:
*
* ```ts
* const PigIdSchema = TypeIDSchema('pig')
* const somePigId = v.parse(PigIdSchema, 'pig_00041061050r3gg28a1c60t3gf')
*
* // somePigId is a TypeID<'pig'> so can be passed to getPig
* const getPig = (id: TypeID<'pig'>) => {...}
* ```
* @param prefix the prefix of the TypeID
* @returns A Valibot schema for TypeId<prefix>
*/
export const TypeIDSchema = <T extends string>(prefix: T) =>
v.custom<TypeID<T>>(
(value: unknown) => {
if (typeof value !== 'string') return false
try {
fromString(value, prefix)
return true
} catch (error: unknown) {
console.error('error in id.ts', error) // ??
return false
}
},
(issue) =>
`${issue.received} is not a valid "${prefix}" TypeID. Valid example: "${prefix}_00041061050r3gg28a1c60t3gf"`,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment