UNPKG

graphql-scalars

Version:

A collection of scalar types not included in base GraphQL.

42 lines 1.47 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"); const ISBN_REGEX_ARR = [ /^(?:ISBN(?:-10)?:? *((?=\d{1,5}([ -]?)\d{1,7}\2?\d{1,6}\2?\d)(?:\d\2*){9}[\dX]))$/i, /^(?:ISBN(?:-13)?:? *(97(?:8|9)([ -]?)(?=\d{1,5}\2?\d{1,7}\2?\d{1,6}\2?\d)(?:\d\2*){9}\d))$/i ]; const validate = (value) => { if (typeof value !== 'string') { throw new TypeError(`Value is not string: ${value}`); } let valid = false; for (const regex of ISBN_REGEX_ARR) { if (regex.test(value)) { valid = true; break; } } if (!valid) { throw new TypeError(`Value is not a valid ISBN number: ${value}`); } return value; }; exports.default = new definition_1.GraphQLScalarType({ name: `ISBN`, description: `A field whose value is a ISBN-10 or ISBN-13 number: https://en.wikipedia.org/wiki/International_Standard_Book_Number.`, serialize(value) { return validate(value); }, parseValue(value) { return validate(value); }, parseLiteral(ast) { if (ast.kind !== language_1.Kind.STRING) { throw new error_1.GraphQLError(`Can only validate strings as ISBN numbers but got a: ${ast.kind}`); } return validate(ast.value); } }); //# sourceMappingURL=ISBN.js.map