'How do I use graphql-type-json scalar in Nest.js code first appraoch
I've npm installed graphql-type-json and the types. How do I use it in a code first approach, where JSONObject is the scalar in the example below.
import {Field, Int, InputType} from 'type-graphql';
import {Direction, MessageType} from '../interfaces/message.interface';
@InputType()
export class MessageInput {
@Field()
readonly to: string;
@Field()
readonly type: MessageType;
@Field()
readonly direction: Direction;
@Field()
readonly body: **JSONObject**;
}
Solution 1:[1]
I found this method and it worked for me. Might not be the code-first approach but I guess it would suffice until you figure it out :)
import { Field, ObjectType } from 'type-graphql';
import JSON from 'graphql-type-json';
@ObjectType()
export class YourClass {
@Field(() => JSON)
myProperty: any;
}
Solution 2:[2]
It's not super elegant, but I did it by creating a @Scalar
decorated class that wraps the GraphQLJSON
object:
// json.scalar.ts
import { Scalar, CustomScalar } from '@nestjs/graphql';
import * as GraphQLJSON from 'graphql-type-json';
@Scalar('JSON', type => Object)
export class JsonScalar implements CustomScalar<string, any> {
name = GraphQLJSON.name;
description = GraphQLJSON.description;
serialize = GraphQLJSON.serialize;
parseValue = GraphQLJSON.parseValue;
parseLiteral = GraphQLJSON.parseLiteral;
}
Then I just added JsonScalar
to the resolvers
section in the module.
You can use it in a resolver with @Query(returns => Object)
, same goes with other places you need to specify type to nest, it's just Object
Nestjs should really allow us to add a scalar by object rather than class, surprised it's not a thing. I was switching from schema-first to code-first and ran into this issue.
Solution 3:[3]
You can create a @Scalar()
type using the approach described in the docs
Solution 4:[4]
Code first
npm install graphql-type-json
or yarn add graphql-type-json
import { GraphQLJSON } from 'graphql-type-json';
type JSONValue =
| string
| number
| boolean
| null
| { [x: string]: JSONValue }
| Array<JSONValue>;
export class SampleModel {
@Field(() => GraphQLJSON, { nullable: true })
data?: JSONValue; // It can different e.g If you're using Prisma ORM => "Prisma.JsonValue"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Antoni |
Solution 2 | |
Solution 3 | Jay McDoniel |
Solution 4 |