UNPKG

graphql-compose

Version:

GraphQL schema builder from different data sources with middleware extensions.

47 lines (38 loc) 1.37 kB
import { GraphQLScalarType } from 'graphql'; import { GraphQLError } from 'graphql/error'; import { Kind } from 'graphql/language'; export default new GraphQLScalarType({ name: 'Date', serialize: function serialize(value) { if (typeof value === 'string' && /^(\d{4})-(\d{2})-(\d{2})T((\d{2}):(\d{2}):(\d{2}))\.(\d{3})Z$/.test(value)) { return value; } if (!(value instanceof Date)) { throw new TypeError('Field error: value is not an instance of Date'); } if (isNaN(value.getTime())) { throw new TypeError('Field error: value is an invalid Date'); } return value.toJSON(); }, parseValue: function parseValue(value) { var date = new Date(value); if (isNaN(date.getTime())) { throw new TypeError('Field error: value is an invalid Date'); } return date; }, parseLiteral: function parseLiteral(ast) { if (ast.kind !== Kind.STRING) { throw new GraphQLError('Query error: Can only parse strings to buffers but got a: ' + ast.kind, [ast]); } var result = new Date(ast.value); if (isNaN(result.getTime())) { throw new GraphQLError('Query error: Invalid date', [ast]); } if (ast.value !== result.toJSON()) { throw new GraphQLError('Query error: Invalid date format, only accepts: YYYY-MM-DDTHH:MM:SS.SSSZ', [ast]); } return result; } });