2

I receive LASTUPDATE: 1579443364 response from an external API,
How can I define the data type in the schema in order to convert it to Date format?

Like this format: Mon Jan 19 2020 00:44:04

GraphQL schema language supports:

Int
Float
String
Id
Boolean

enter image description here

Pep
  • 97
  • 1
  • 2
  • 9
  • It's not a date, it's an Int – jonrsharpe Jan 19 '20 at 14:29
  • Yes, but I want to convert it into this format " Mon Jan 19 2020 00:44:04 " – Pep Jan 19 '20 at 14:34
  • How is that anything to do with the schema, though? The schema describes the API, which in this case is an Int. if you want to parse that and e.g. store it differently, that's up to the code behind the API. – jonrsharpe Jan 19 '20 at 14:46

2 Answers2

7

You can use a custom scallar that parse the Int into date If you are using apollo server you can try something like this

import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';

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

And then

scalar Date

type MyType {
   created: Date
}

You can take a closer look here https://www.apollographql.com/docs/graphql-tools/scalars/ Here are some other useful scalars https://github.com/Urigo/graphql-scalars

1

Long answer: you should define a scalar type to represent your date information (as documented and also answered)

Short answer: you may use a 3rd party lib to take care for you (such as https://www.npmjs.com/package/graphql-iso-date (you use node so this one should suit your needs)

Either way, I assume the numeric value is a timestamp so you should use the resolve function to translate this numuber to a valid date

ymz
  • 6,602
  • 1
  • 20
  • 39