UNPKG

graphql-scalars

Version:

A collection of scalar types not included in base GraphQL.

40 lines (39 loc) 1.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GraphQLCuid2 = void 0; const graphql_1 = require("graphql"); const error_js_1 = require("../error.js"); const CUID2_REGEX = /^[a-z][a-z0-9]{1,31}$/; const validateCuid2 = (value, ast) => { if (typeof value !== 'string') { throw (0, error_js_1.createGraphQLError)(`Value is not string: ${value}`, ast ? { nodes: ast } : undefined); } if (!CUID2_REGEX.test(value)) { throw (0, error_js_1.createGraphQLError)(`Value is not a valid cuid2: ${value}`, ast ? { nodes: ast } : undefined); } return value; }; const specifiedByURL = 'https://github.com/paralleldrive/cuid2'; exports.GraphQLCuid2 = new graphql_1.GraphQLScalarType({ name: 'Cuid2', description: `A field whose value conforms to the cuid2 format, as specified in ${specifiedByURL}`, serialize: validateCuid2, parseValue: validateCuid2, parseLiteral(ast) { if (ast.kind !== graphql_1.Kind.STRING) { throw (0, error_js_1.createGraphQLError)(`Can only validate strings as cuid2 but got: ${ast.kind}`, { nodes: [ast], }); } return validateCuid2(ast.value, ast); }, specifiedByURL, extensions: { codegenScalarType: 'string', jsonSchema: { title: 'Cuid2', type: 'string', pattern: CUID2_REGEX.source, }, }, });