尝试创建 GraphQL 指令时出现类型错误

时间:2020-12-23 09:41:11

标签: node.js typescript graphql apollo-server

我正在使用 Apollo-Server/TypeScript 并利用 graphql-tool 的 makeExecutableSchema() 来设置架构/指令。

我目前在尝试添加准系统简单的 GraphQL 指令时遇到此错误:

TypeError: Class constructor SchemaDirectiveVisitor cannot be invoked without 'new' at new AuthDirective
(/home/node/app/src/api/directives/AuthDirective.ts:58:42)

这是架构的设置:

import AuthDirective, { authTypeDefs } from "./directives/AuthDirective";
import { makeExecutableSchema } from "graphql-tools";

const schema = makeExecutableSchema({
  resolvers: [...],
  typeDefs: [...], // authTypeDefs is included here
  schemaDirectives: {
    auth: AuthDirective,
  },
});

export default schema;

AuthDirective 文件:

import { SchemaDirectiveVisitor } from "graphql-tools";
import { defaultFieldResolver } from "graphql";

export default class AuthDirective extends SchemaDirectiveVisitor {
  public visitFieldDefinition(field) {
    console.log("VISIT FIELD: ", field);
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async function (...args) {
      return resolve.apply(this, args);
    };
  }
}

export const authTypeDefs = `
  enum AppRole {
    USER
    ADMIN
  }

  directive @auth(
    requires: AppRole! = USER
  ) on FIELD_DEFINITION 
`;

我一直在关注文档 here。一切似乎都井井有条,但我可能忽略了一些东西。

荒谬的是,错误是关于 AuthDirective 文件中的第 58 行。 该文件只有 23/24 行。

1 个答案:

答案 0 :(得分:0)

解决了这个问题。我已经使用 graphql-tools 指令解析器(而不是基于类的 SchemaDirectiveVisitor 方式)改变了实现指令的方式。文档 here