简体   繁体   中英

Nestjs graphql, How to make refer to it self input type?

I want to make nestjs graphql input type with refer to it self. so it can be nested object.

I want to do is

type Tree = {
  [key: string]: Tree | string | number;
};

// it can be like
const example1: Tree = {
  user: {
    name: 'foo',
  },
};

//or
const example2: Tree = {
  id: {
    $eq: 1,
  },
};

Change it to graphql input type, but i can not figure out.

I tried to do is

@InputType()
export class TreeClass {
  @Field(() => TreeClass)
  @IsNotEmpty()
  tree: string;
}

@InputType()
export class AddQsInput {
...
  @Field(() => TreeClass, { nullable: true })
  @IsNotEmpty()
  @IsOptional()
  filters?: any;
...
}

error like

GraphQLError: Cannot reference Input Object "TreeClass" within itself through a series of non-null fields: "tree".

I found how to.

It isn't perfect answer, but it can be replacement.

The answer is 'graphql-type-json'.

With this, You can write any type of JSON in input or type

how to use

with npm

$ npm i --save graphql-type-json

or with yarn

$ yarn add graphql-type-json

and then

//app.module.ts
import GraphQLJSON from 'graphql-type-json';

@Module({
  imports: [
    GraphQLModule.forRoot({
      resolvers: { JSON: GraphQLJSON },
    }),
  ],
})
export class AppModule {}
//user.input.ts

...
@Field((type) => GraphQLJSON)
info: JSON;
...

reference

nestjs-scalartype

graphql-type-json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM