Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date and Json in type definition for graphql

Tags:

graphql

apollo

Is it possible to have a define a field as Date or JSON in my graphql schema ?

type Individual {     id: Int     name: String     birthDate: Date     token: JSON } 

actually the server is returning me an error saying :

Type "Date" not found in document. at ASTDefinitionBuilder._resolveType (****node_modules\graphql\utilities\buildASTSchema.js:134:11) 

And same error for JSON...

Any idea ?

like image 758
Mohamed Taboubi Avatar asked Apr 06 '18 13:04

Mohamed Taboubi


People also ask

Does GraphQL have date type?

GraphQL comes with default scalar types like Int, Float, String, Boolean and ID. But dates and times have to be defined as custom scalars like Date or timestamp etc.

How do you define a type in GraphQL?

A GraphQL object type has a name and fields, but at some point those fields have to resolve to some concrete data. That's where the scalar types come in: they represent the leaves of the query. We know this because those fields don't have any sub-fields - they are the leaves of the query.


1 Answers

Have a look at custom scalars: https://www.apollographql.com/docs/graphql-tools/scalars.html

create a new scalar in your schema:

scalar Date  type MyType {    created: Date } 

and create a new resolver:

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 parseInt(ast.value, 10); // ast value is always in string format       }       return null;     },   }), 
like image 51
Andreas Köberle Avatar answered Sep 19 '22 08:09

Andreas Köberle