Skip to content

Instantly share code, notes, and snippets.

@rrakso
Created September 6, 2023 19:22
Show Gist options
  • Save rrakso/a6e13d51ae36d3ee4b45e34dd1c5744b to your computer and use it in GitHub Desktop.
Save rrakso/a6e13d51ae36d3ee4b45e34dd1c5744b to your computer and use it in GitHub Desktop.
Custom UUID Scalar for GraphQL on NestJS. Remember to properly set our "custom" type → https://docs.nestjs.com/graphql/resolvers#args-decorator-options
// Modified "vanilla" example. It uses the `isUUID()` function from the `class-validator` package.
import { isUUID } from 'class-validator';
import { GraphQLScalarType, StringValueNode } from 'graphql';
function validate(uuid: unknown): string | never {
if (!isUUID(uuid)) {
throw new Error('The given value is not a UUID string.');
}
return uuid as string;
}
export const UuidScalar = new GraphQLScalarType({
name: 'UUID',
description: 'Universally Unique Identifier (UUID). Example: `123e4567-e89b-12d3-a456-426614174000`.',
serialize: (value) => validate(value),
parseValue: (value) => validate(value),
parseLiteral: (ast: StringValueNode) => validate(ast.value),
});
// Source: https://docs.nestjs.com/graphql/scalars#create-a-custom-scalar
import { GraphQLScalarType, StringValueNode } from 'graphql';
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function validate(uuid: unknown): string | never {
if (typeof uuid !== 'string' || !regex.test(uuid)) {
throw new Error('Invalid UUID');
}
return uuid;
}
export const UuidScalar = new GraphQLScalarType({
name: 'UUID',
description: 'Universally Unique Identifier (UUID). Example: `123e4567-e89b-12d3-a456-426614174000`.',
serialize: (value) => validate(value),
parseValue: (value) => validate(value),
parseLiteral: (ast: StringValueNode) => validate(ast.value),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment