简体   繁体   English

如何在graphql-compose中使用自定义输入类型?

[英]How to use custom input type in graphql-compose?

I'm using mongodb and graphql-compose-mongoose in order to generate the Graphql schema.我正在使用 mongodb 和 graphql-compose-mongoose 来生成 Graphql 模式。 However I'm adding authentication mutations and I want to add graphql input for one of the queries.但是,我正在添加身份验证突变,并且我想为其中一个查询添加 graphql 输入。 I saw in the documentation that args.filter can receive an input:我在文档中看到args.filter可以接收输入:

CityTC.addResolver({
  kind: 'query',
  name: 'findMany',
  args: {
    filter: `input CityFilterInput {
      code: String!
    }`,
    limit: {
      type: 'Int',
      defaultValue: 20,
    },
    skip: 'Int',
    // ... other args if needed
  },
  type: [CityTC], // array of cities
  resolve: async ({ args, context }) => {
    return context.someCityDB
      .findMany(args.filter)
      .limit(args.limit)
      .skip(args.skip);
  },
});

However I'm not using any filter.但是我没有使用任何过滤器。 I want to create an input like this:我想创建一个这样的输入:

const AuthPayloadTC = schemaComposer.createObjectTC({
  name: 'AuthPayloadTC',
  fields: {
      jwtToken: 'String!'
  }
});

AuthPayloadTC.addResolver({
  name: 'userConnectData',
  type: AuthPayloadTC,
  args: `input {
    accessToken String!
    provider String!
  }`,
  resolve: async ({ source, args, context, info }) => {
      const { accessToken, provider } = args;
      return {
          jwtToken: '12345678'
      }
  }
})

This doesn't work because my input is not parsed to a the kind of object that args field expects.这不起作用,因为我的输入没有被解析为args字段期望的那种对象。 I did notice that graphql-compose exposes InputTypeComposer however I couldn't any example on how to use it in a resolver.我确实注意到 graphql-compose 公开了InputTypeComposer但是我没有任何关于如何在解析器中使用它的例子。

Through some trial and error I figured out this out:通过一些试验和错误,我发现了这一点:

import { schemaComposer, toInputObjectType } from 'graphql-compose'

const InputTC = schemaComposer.createObjectTC({
  name: 'UserConnectDataInput',
  fields: {
    accessToken: 'String!'
  }
});

const InputITC = toInputObjectType(InputTC);

AuthPayloadTC.addResolver({
  name: 'userConnectData',
  type: AuthPayloadTC,
  args: {
    input: InputITC
  },
  resolve: async ({ source, args, context, info }) => {
      const { accessToken, provider, email } = args;
      return {
          jwtToken: '12345678'
      }
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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