Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON type in GraphQL #111

Closed
bcba25 opened this issue Jan 18, 2019 · 11 comments
Closed

JSON type in GraphQL #111

bcba25 opened this issue Jan 18, 2019 · 11 comments

Comments

@bcba25
Copy link

bcba25 commented Jan 18, 2019

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 ?

@kamilmysliwiec
Copy link
Member

https://docs.nestjs.com/graphql/scalars

@vagostep
Copy link

@kamilmysliwiec please add an example of how to implement this package in code first way

@adityaloshali
Copy link

@kamilmysliwiec please add an example of how to implement this package in code first way

@kamilmysliwiec When i inject resolvers: { JSON: GraphQLJSON }, in the root config for the code first approach. It gives the Error: "JSON" defined in resolvers, but not in schema. how do we resolve this?

@dennis-b
Copy link

dennis-b commented Oct 2, 2019

any example how to use it with code first ?

@johannesschobel
Copy link

i am also struggling with the code-first approach and custom scalars.

@johannesschobel
Copy link

johannesschobel commented 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

@gkTim
Copy link

gkTim commented Mar 1, 2020

Here what I did to simply output JSON in an ObjectType:

import { Field, ObjectType } from 'type-graphql';
import graphqlTypeJson from 'graphql-type-json';

@ObjectType()
export class JsonTest {
  @Field(() => graphqlTypeJson, { nullable: true })
  public result?: any;
}

For my use case all is working fine.

@merq-rodriguez
Copy link

merq-rodriguez commented May 13, 2020

@kamilmysliwiec por favor agregue un ejemplo de cómo implementar este paquete en código de primera manera

@kamilmysliwiec Cuando inyecto resolvers: {JSON: GraphQLJSON}, en la configuración raíz para el primer enfoque de código. Da el error: "JSON" definido en resolvers, pero no en esquema. ¿Cómo resolvemos esto?

I also have that problem, could you solve it?

@jp-ryuji
Copy link

jp-ryuji commented May 20, 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

@cramhead
Copy link

Works with also

import {  GraphQLJSONObject } from 'graphql-type-json';
@ObjectType()
export class SomeClass {
  @Field(() => GraphQLJSONObject, { nullable: true })
  json?: JSON;
}

@s4kh

This comment has been minimized.

@nestjs nestjs locked and limited conversation to collaborators Jun 22, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests