ApolloServer不触发自定义指令

时间:2019-02-13 14:30:59

标签: graphql apollo-server

我正在尝试基于apollo服务器文档编写一些身份验证逻辑,但是似乎没有触发。这是我的代码:

// schemas/auth-schema.js

import gql from 'graphql-tag';

export const typeDefs = gql`
  directive @auth(requires: Role = ADMIN) on OBJECT | FIELD_DEFINITION
`;

// directives/auth-directive.js
import { SchemaDirectiveVisitor } from 'apollo-server';

export default class AuthDirective extends SchemaDirectiveVisitor {
  visitObject(type) {
    console.log('HERE');
  }
  visitSchema() {
    console.log('HERE');
  }
  visitFieldDefinition() {
    console.log('HERE');
  }
}
// schemas/post-schema.js

import gql from 'graphql-tag';
import { Post } from '../models';

export const typeDefs = gql`
  type Post @auth(requires: ADMIN) {
    body: String!
    description: String!
    id: ID!
    image: String!
    publishedAt: DateTime
    readingTime: Int!
    slug: String!
    title: String!
  }

  input PostInput {
    body: String!
    description: String!
    image: String!
    publishedAt: DateTime
    title: String!
  }

  extend type Query {
    posts: [Post!]! @auth(requires: ADMIN)
  }

  extend type Mutation {
    addPost(input: PostInput!): Post! @auth(requires: ADMIN)
  }
`;

export const resolvers = {
  Query: {
    posts: () => Post.find({}),
  },
  Mutation: {
    addPost: (_, { input }) => Post.create(input),
  },
};

// index.js

import { ApolloServer } from 'apollo-server';
import mongoose from 'mongoose';
import AuthDirective from './directives/auth-directive';
import * as config from './config';

mongoose.set('useNewUrlParser', true);
mongoose.set('useCreateIndex', true);
mongoose.set('debug', config.env !== 'production');

const server = new ApolloServer({
  modules: [
    require('./schema/auth-schema'),
    require('./schema/date-schema'),
    require('./schema/post-schema'),
    require('./schema/role-schema'),
    require('./schema/user-schema'),
  ],
  schemaDirectives: {
    auth: AuthDirective,
  },
});

async function boot() {
  await mongoose.connect(config.mongo.url);
  await server.listen(config.http.port);
  console.log(`server listening on port ${config.http.port}`);
}

async function shutdown() {
  await server.stop();
  await mongoose.disconnect();
  console.log(`server shutted down`);
  process.exit(0);
}

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

boot();

因此,我尝试过在所有可能的情况下都使用@auth指令,而没有执行任何操作。

type Post @auth(requires: ADMIN) { ... } // not firing

type Query {
  posts: [Post!]! @auth(requires: ADMIN) // not firing
}

这是从控制台评估AdminDirective的结果: enter image description here

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

因此,看一下apollo-server的代码,当您使用modules选项时,内部将使用buildServiceDefinition构建模式。尽管此函数确实合并了所有模块中的指令,但并未传递您的schemaDirectives对象,因此不会应用它。

换句话说,这看起来像是apollo-server本身的错误。您可以提出问题,与此同时,只需使用typeDefsresolvers选项,自己组合必要的文件即可。