【问题标题】:How to set type for Apollo resolver context?如何为 Apollo 解析器上下文设置类型?
【发布时间】:2023-02-03 08:40:55
【问题描述】:

我有一个简单的 Apollo GraphQL 子图,我想在其中为我的解析器中的上下文 arg 设置类型。

我创建了一个解析器并将上下文的类型设置如下:

interface Context {
  dataSources: {
    shopify: Shopify;
  }
}

const server = new ApolloServer({
  schema: buildSubgraphSchema({ 
    typeDefs,
    resolvers: {
      Query: {
        shop(_, _args, ctx: Context) {
          console.log("ctx:", ctx)
        },
      }
    }
  }),
  dataSources: () => ({
    shopify: new Shopify()
  })
});

但是,我设置的 Context 接口似乎与我的解析器期望的类型不兼容,我收到以下错误:

Argument of type '{ typeDefs: any; resolvers: { Query: { shop(_: any, _args: any, ctx: Context): void; }; }; }' is not assignable to parameter of type 'DocumentNode | (GraphQLSchemaModule | DocumentNode)[] | LegacySchemaModule'.
  Types of property 'resolvers' are incompatible.
    Property 'Query' is incompatible with index signature.
      Type '{ shop(_: any, _args: any, ctx: Context): void; }' is not assignable to type 'GraphQLScalarType<unknown, unknown> | { [enumValue: string]: string | number; } | { [fieldName: string]: GraphQLFieldResolver<any, unknown, any, unknown> | { requires?: string | undefined; resolve: GraphQLFieldResolver<...>; }; }'.
        Types of property 'shop' are incompatible.
          Type '(_: any, _args: any, ctx: Context) => void' is not assignable to type 'string | number | GraphQLFieldResolver<any, unknown, any, unknown> | { requires?: string | undefined; resolve: GraphQLFieldResolver<any, unknown, any, unknown>; } | undefined'.
            Type '(_: any, _args: any, ctx: Context) => void' is not assignable to type 'GraphQLFieldResolver<any, unknown, any, unknown>'.
              Types of parameters 'ctx' and 'context' are incompatible.
                Type 'unknown' is not assignable to type 'Context'.ts(2345)

如何为我的解析器设置上下文类型,以便我可以访问接口和数据源等?

【问题讨论】:

    标签: javascript node.js typescript graphql apollo


    【解决方案1】:

    我遇到了同样的问题,虽然我仍在寻找更好的解决方案,但暂时您可以使用它来解决这个问题:

    Query: {
        shop(_, _args, ctx) {
          const {datasource} = ctx as Context;
          datasource.shopify; //Shopify
        },
      }
    

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2017-01-11
      • 2021-08-22
      • 1970-01-01
      • 2017-05-04
      • 2019-11-06
      • 2021-10-14
      • 2020-06-30
      • 2019-08-01
      相关资源
      最近更新 更多