graphql-scalars
Version:
A collection of scalar types not included in base GraphQL.
62 lines (61 loc) • 1.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphQLULID = void 0;
const graphql_1 = require("graphql");
const error_js_1 = require("../error.js");
const ULID_REGEX = /^[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}$/i;
/**
* Check if a ULID is valid according to the official spec
* @param id The ULID to test
* @returns True if valid, false otherwise
*/
const isValid = (id) => {
return typeof id === 'string' && ULID_REGEX.test(id);
};
const validate = (value, ast) => {
if (typeof value !== 'string') {
throw (0, error_js_1.createGraphQLError)('ULID can only parse String', ast
? {
nodes: ast,
}
: undefined);
}
if (!isValid(value)) {
throw (0, error_js_1.createGraphQLError)('Invalid ULID format', ast
? {
nodes: ast,
}
: undefined);
}
// Return the normalized uppercase version
return value.toUpperCase();
};
exports.GraphQLULID = new graphql_1.GraphQLScalarType({
name: 'ULID',
description: 'A ULID (Universally Unique Lexicographically Sortable Identifier) is a 26-character ' +
'string that is URL-safe, case-insensitive, and lexicographically sortable.',
serialize(value) {
return validate(value);
},
parseValue(value) {
return validate(value);
},
parseLiteral(ast) {
if (ast.kind === graphql_1.Kind.STRING) {
return validate(ast.value, ast);
}
throw (0, error_js_1.createGraphQLError)(`ULID can only parse String but got '${ast.kind}'`, {
nodes: [ast],
});
},
extensions: {
codegenScalarType: 'string',
jsonSchema: {
title: 'ULID',
type: 'string',
pattern: ULID_REGEX.source,
minLength: 26,
maxLength: 26,
},
},
});