UNPKG

graphql-scalars

Version:

A collection of scalar types not included in base GraphQL.

46 lines 1.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const definition_1 = require("graphql/type/definition"); const error_1 = require("graphql/error"); const language_1 = require("graphql/language"); class RegularExpression extends definition_1.GraphQLScalarType { constructor(name, regex, options = {}) { const REGEX = new RegExp(regex); const errorMessage = options.errorMessage ? options.errorMessage : (r, v) => `Value does not match the regular expression ${r}: ${v}`; super({ name, description: `A field whose value matches the provided regular expression ${regex}.`, serialize(value) { if (typeof value !== 'string') { throw new TypeError(`Value is not string: ${value}`); } if (!REGEX.test(value)) { throw new TypeError(errorMessage(regex, value)); } return value; }, parseValue(value) { if (typeof value !== 'string') { throw new TypeError(`Value is not string: ${value}`); } if (!REGEX.test(value)) { throw new TypeError(errorMessage(regex, value)); } return value; }, parseLiteral(ast) { if (ast.kind !== language_1.Kind.STRING) { throw new error_1.GraphQLError(`Can only validate strings as regular expressions but got a: ${ast.kind}`); } if (!REGEX.test(ast.value)) { throw new TypeError(errorMessage(regex, ast.value)); } return ast.value; }, }); } } exports.default = RegularExpression; //# sourceMappingURL=RegularExpression.js.map