简体   繁体   中英

value.getTime is not a function GraphQL custom scalar Date

I receive LASTUPDATE: 1579452599 response from an external API,

I want to parse the value in this format: Mon Jan 19 2020 13:44:04, I tried using custom scallar, but I'm having this error:

value.getTime is not a function

在此处输入图片说明

What am I doing wrong?

This is my code,

resolvers.js

import fetch from 'node-fetch';
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';

export const resolvers = {
  Query: {
    getCrypto: async() => {
      const response = await fetch('https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=USD&api_key=260d15e639be7b967c2b0e4f9f3b6d656897ccbdfe772b1d24818d9f96d3a6ed')

      let data = await response.json()
      return data.Data[0].RAW.USD;

    }
  },
  Date: new GraphQLScalarType({
    name: 'Date',
    description: 'Date custom scalar type',
    parseValue(value) {
      return new Date(value); // value from the client
    },
    serialize(value) {
      console.log(value)
      return value.getTime(); // value sent to the client
    },
    parseLiteral(ast) {
      if (ast.kind === Kind.INT) {
        return parseInt(ast.value, 10); // ast value is always in string format
      }
      return null;
    },
  })
};

schema.graphql

type CryptoCurrency {
  FROMSYMBOL: String
  PRICE: Float
  TOSYMBOL: String  
  LASTUPDATE: Date
}

type Query {
  getCrypto: CryptoCurrency
}

scalar Date
type MyType {
   created: Date
}


In console I see the value在此处输入图片说明

In case anyone else comes here from a google search for a similar issue
You should convert LASTUPDATE from timestamp to actual date, and have to multiply by 1000 because Javascript uses milliseconds.

   serialize(value) {
                console.log( new Date(value).toISOString())
                return new Date(value * 1000).toISOString(); // value sent to the client
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM