Skip to content

Instantly share code, notes, and snippets.

@prowlee
Forked from langpavel/GraphQLTimestamp.js
Created July 28, 2023 08:46
Show Gist options
  • Select an option

  • Save prowlee/640efd800c8ed98b301064a7b38938d0 to your computer and use it in GitHub Desktop.

Select an option

Save prowlee/640efd800c8ed98b301064a7b38938d0 to your computer and use it in GitHub Desktop.

Revisions

  1. @langpavel langpavel revised this gist May 6, 2016. 1 changed file with 5 additions and 4 deletions.
    9 changes: 5 additions & 4 deletions GraphQLTimestamp.js
    Original file line number Diff line number Diff line change
    @@ -13,8 +13,9 @@ function serializeDate(value) {
    }

    function parseDate(value) {
    if (value === null)
    if (value === null) {
    return null;
    }

    try {
    return new Date(value);
    @@ -23,7 +24,7 @@ function parseDate(value) {
    }
    }

    function parseDateFromLiteral (ast) {
    function parseDateFromLiteral(ast) {
    if (ast.kind === Kind.INT) {
    const num = parseInt(ast.value, 10);
    return new Date(num);
    @@ -36,11 +37,11 @@ function parseDateFromLiteral (ast) {
    const TimestampType = new GraphQLScalarType({
    name: 'Timestamp',
    description:
    'The javascript `Date` as integer. Type represents date and time '+
    'The javascript `Date` as integer. Type represents date and time ' +
    'as number of milliseconds from start of UNIX epoch.',
    serialize: serializeDate,
    parseValue: parseDate,
    parseLiteral: parseDateFromLiteral,
    });

    export default TimestampType
    export default TimestampType;
  2. @langpavel langpavel created this gist May 5, 2016.
    46 changes: 46 additions & 0 deletions GraphQLTimestamp.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    import { Kind } from 'graphql/language';
    import { GraphQLScalarType } from 'graphql';

    function serializeDate(value) {
    if (value instanceof Date) {
    return value.getTime();
    } else if (typeof value === 'number') {
    return Math.trunc(value);
    } else if (typeof value === 'string') {
    return Date.parse(value);
    }
    return null;
    }

    function parseDate(value) {
    if (value === null)
    return null;

    try {
    return new Date(value);
    } catch (err) {
    return null;
    }
    }

    function parseDateFromLiteral (ast) {
    if (ast.kind === Kind.INT) {
    const num = parseInt(ast.value, 10);
    return new Date(num);
    } else if (ast.kind === Kind.STRING) {
    return parseDate(ast.value);
    }
    return null;
    }

    const TimestampType = new GraphQLScalarType({
    name: 'Timestamp',
    description:
    'The javascript `Date` as integer. Type represents date and time '+
    'as number of milliseconds from start of UNIX epoch.',
    serialize: serializeDate,
    parseValue: parseDate,
    parseLiteral: parseDateFromLiteral,
    });

    export default TimestampType