迁移到 Typescript 时无法弄清楚如何使用 Schema 指令

Can't figure out how to use Schema Directives when moving to Typescript

我花了几天时间将我的 GraphQL 服务器重写为 Typescript,但最终还是无法定义 Schema 指令。已经花了很多时间谷歌搜索,但没有找到“更高级”的 Apollo GraphQL with Typescript 的例子。

当我使用纯 Javascript 时,它非常适合我,没有任何问题,我的指令如下所示:

// TS but no difference from JS in terms of extended class or method overriden
export default class UserAuthDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field: any, details: any) {
    field._requiredRole = this.args.role
    const { resolve = defaultFieldResolver } = field
    field.resolve = function (...args: any) {
      // LOGIC CHECKING ROLES
    }
  }
}

我使用 makeExecutableSchema 来自 graphql-tools 库,如下所示:

// Again basically identical with original JS
const schema = makeExecutableSchema({
  typeDefs: mergeTypes(types, { all: true }),
  resolvers: loadResolvers(),
  logger: {
    log: (e) => logger.error(e.message, e),
  },
  allowUndefinedInResolve: false,
  inheritResolversFromInterfaces: true,
  resolverValidationOptions: {
    allowResolversNotInSchema: false,
    requireResolversForResolveType: true,
  },
  schemaDirectives: {
    userHas: UserAuthDirective,
    // ^^^ Here I'm getting. "Type 'typeof UserAuthDirective' is not assignable to type 'typeof SchemaDirectiveVisitor'. Types of property 'visitSchemaDirectives' are incompatible."
  },
})

SchemaDirectiveVisitor 的构造函数受到保护,因此我无法从那里实例化 class。 我不是真正的高级 Typescript 用户,所以也许我只是完全错误地理解它或缺少一些基本概念,但我真的坚持这一点,并且很高兴收到任何提示或猜测我可能做错了什么。

谢谢 :-)

我在你的 visitFieldDefinition 方法中看到两个参数。

此 class 的实现因 graphql 的实现而异。

如果您使用的是apollo-server:

实现SchemaDirectiveVisitor时需要重写其中一个访问方法,这些方法只有一个参数。因此,该方法被重载而不是被覆盖。

请参考以下页面:

https://www.apollographql.com/docs/apollo-server/schema/creating-directives/

如果您使用的是graphql-tools:

该方法有 2 个参数,看起来像 visitFieldDefinition(field: GraphQLField<any, any>, details: { objectType: GraphQLObjectType | GraphQLInterfaceType })

请参考以下页面:

https://www.graphql-tools.com/docs/legacy-schema-directives/#implementing-schema-directives

您需要确保从正确的包中导入 SchemaDirectiveVisitor -- graphql-tools 而不是 apollo-server。根据每个包的版本,很可能每个包导出的 SchemaDirectiveVisitor 类 彼此不兼容。