question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

JSON type in GraphQL

See original GitHub issue

I’m submitting a…


[ ] Regression 
[ ] Bug report
[ ] Feature request
[X] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

https://www.apollographql.com/docs/graphql-tools/scalars.html Is it possible to implement JSON as a GraphQL type using graphql-type-json or any other package or way? Sorry I haven’t found any thread or examples on this, so wondering if its possible to do in nest like its done in Express

My GraphQL Module

GraphQLModule.forRoot({
            typePaths: ['./**/*.graphql'],
            installSubscriptionHandlers: true,
            definitions: {
                path: join(process.cwd(), 'src/graphql.schema.ts'),
                outputAs: 'class',
            },
            context: ({ req }) => ({ headers: req.headers, req: req }),
        }),

Is it possible to include the type resolvers here ?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

20reactions
jp-ryujicommented, May 24, 2020

JSON type for the code first approach. This works in my environment, "@nestjs/graphql": "^7.3.7".

yarn add graphql-type-json
yarn add -D @types/graphql-type-json
import graphqlTypeJson from 'graphql-type-json'
import { Field, ObjectType } from '@nestjs/graphql'

@ObjectType()
export class SomeClass {
  @Field(() => graphqlTypeJson, { nullable: true })
  json?: object
}

Then you see the following in your schema.gql.

type SomeClass {
  json: JSON
}

"""
The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSON
18reactions
johannesschobelcommented, Dec 11, 2019

ok guys… i managed to solve this issue. However, i was not able to directly include any of the existing packages (although this may be possible for sure).

Here is, what i did: First, i had to create a plain JSONObject class like this:

export class JSONObject {}

Then, i created a new Scalar for this JSONObject i want to output

@Scalar('JSONObject', type => JSONObject)
export class JSONObjectScalar implements CustomScalar<object, object> {
  description = 'JSONObject custom scalar type';

  parseValue(value: object): object {
    return value; // this is the value a client sends to the server
  }

  serialize(value: object): object {
    return value; // this is the value the server sends to the client
  }

  parseLiteral(ast: any): object {
    if (ast.kind === Kind.OBJECT) {
      return new Object(ast.value);
    }
    return null;
  }
}

Then i “registered” this Scalar somewhere (for example in the module i want to use it):

@Module({
  providers: [
    FooResolver, 
    // ... other providers like services and stuff
    JSONObjectScalar
  ],
})
export class FooModule {}

and finally use the newly defined Scalar in an ObjectType() or InputType() like so:

import { Field, ID, ObjectType } from 'type-graphql';
import { JSONObjectScalar, JSONObject } from 'src/common/scalars/jsonobject.scalar';

@ObjectType()
export class Foo {
  @Field(type => ID)
  id: string;

  // ... some properties here 

  @Field(type => JSONObject, { ... })
  payload: object
}

I really hope, this helps someone. Downside, with this approach is, that you need a dedicated JSONObject class. I was not able to use Object (or object) to achieve the same. Anyway - this works for me 😉

All the best

Read more comments on GitHub >

github_iconTop Results From Across the Web

JSON scalar type for GraphQL.js - GitHub
GraphQLJSON can represent any JSON-serializable value, including scalars, arrays, and objects. GraphQLJSONObject represents specifically JSON objects, ...
Read more >
Custom scalars - Apollo GraphQL Docs
For example, the graphql-type-json package defines the GraphQLJSON object, which is an instance of GraphQLScalarType . You can use this object to define...
Read more >
Class: GraphQL::Types::JSON
An untyped JSON scalar that maps to Ruby hashes, arrays, strings, integers, floats, booleans and nils. This should be used judiciously because it...
Read more >
Assigning JSON in a GraphQL type in Nodejs - Stack Overflow
In that case, I need a another type (which should be a JSON type) to map these responses. Unfortunately, it is not available...
Read more >
Schemas and Types - GraphQL
On this page, you'll learn all you need to know about the GraphQL type system and how it describes what data can be...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found