首页 > 解决方案 > 尝试创建 GraphQL 指令时出现 TypeError

问题描述

我正在使用 Apollo-Server/TypeScript 并利用 graphql-toolmakeExecutableSchema()来设置模式/指令。

我目前在尝试添加准系统简单的 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 
`;

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

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

标签: node.jstypescriptgraphqlapollo-server

解决方案


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


推荐阅读