apollo-server-express,graphql自定义架构指令

时间:2019-07-16 20:21:08

标签: express graphql apollo-server

这对我来说很奇怪。 根据{{​​3}}文档,我将我的Auth SchemaDirective设置如下:

class RequireAuthDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async (...args) => {
      let [, params, { req, res, connection }] = args;
      let { user } = req || connection.context;
      if (!!user) {
        return await resolve.apply(this, args);
      } else {
        throw new AuthenticationError('You must be signed in to view this resource.');
      }
    };
  }
}

在每个QueryMutationSubscription

中都可以正常工作

但是当我使用外部异步方法检查授权时,如下所示:

class RequireAuthDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async (...args) => {
      let [, params, { req, res, connection }] = args;
      let { user } = req || connection.context;
      if (!!user) {
        if (await isAllowed(user.id, field.name, params)) return await resolve.apply(this, args); // ChkPoint
        throw new AuthenticationError('You are not authorized to access this resource.'); 
      } else {
        throw new AuthenticationError('You must be signed in to access this resource.');
      }
    };
  }
}

此方法在QueriesMutations中可以正常使用,但在订阅中却不能!

注意:如果我删除了ChkPoint条件(返回true),它将在订阅中工作。

0 个答案:

没有答案