How to verify UUID format for record keys? #1288
Replies: 1 comment
-
Here's how you can make a custom Type that checks keys and values, and an example of it working with UUID keys: import {
FormatRegistry,
Kind,
Type,
TypeRegistry,
type Static,
type TSchema,
} from '@sinclair/typebox';
import {TypeCompiler} from '@sinclair/typebox/compiler';
import {Value} from '@sinclair/typebox/value';
const Uuid = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
function IsUuid(value: string): boolean {
return Uuid.test(value);
}
FormatRegistry.Set('uuid', (value) => IsUuid(value));
const KeyedRecordKind = 'KeyedRecord' as const;
type KeyedRecordOptions = {
[Kind]: typeof KeyedRecordKind;
type: 'object';
keySchema: TSchema;
valueSchema: TSchema;
};
export function KeyedRecord<K extends TSchema, V extends TSchema>(keySchema: K, valueSchema: V) {
return Type.Unsafe<Record<Extract<Static<K>, PropertyKey>, Static<V>>>({
[Kind]: KeyedRecordKind,
type: 'object',
keySchema,
valueSchema,
} satisfies KeyedRecordOptions);
}
TypeRegistry.Set(KeyedRecordKind, (schema: KeyedRecordOptions, input) => {
if (typeof input !== 'object' || !input || Array.isArray(input)) {
return false;
}
return Object.entries(input).every(
([
key,
value,
]) => {
return Value.Check(schema.keySchema, key) && Value.Check(schema.valueSchema, value);
},
);
});
console.log(
TypeCompiler.Compile(KeyedRecord(Type.String({format: 'uuid'}), Type.Number())).Check({
x: 5,
}),
);
console.log(
TypeCompiler.Compile(KeyedRecord(Type.String({format: 'uuid'}), Type.Number())).Check({
'9aa8a673-8590-4db2-9830-01755844f7c1': 5,
}),
); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to get the following code to log
false
, but it's currently loggingtrue
:The UUID format is straight from https://github.com/sinclairzx81/typebox/blob/60fdafe857089ac908b5fe7741c15c62260b651f/example/formats/uuid.ts.
I would expect
x
to not match because it's clearly not a valid UUID.Beta Was this translation helpful? Give feedback.
All reactions