javascript - 如何在 graphql 解析器中实现守卫

标签 javascript node.js reactjs express graphql

我是 graphql 新手,我正在尝试在我的项目中集成身份验证/授权系统。我在 Medium 上找到了一个例子,但我不明白守卫如何与解析器通信。如果有人知道,我将非常感激。

import { ApolloServer } from 'apollo-server';
import gql from 'graphql-tag';
import { tradeTokenForUser } from './auth-helpers';

const HEADER_NAME = 'authorization';

const typeDefs = gql`
  type Query {
     me: User
     serverTime: String
  }
  type User {
     id: ID!
     username: String!
  }
`;

const resolvers = {
   Query: {
      me: authenticated((root, args, context) => context.currentUser), 
      serverTime: () => new Date(),
   },
   User: {
      id: user => user._id,
      username: user => user.username,
   },
};

const server = new ApolloServer({
   typeDefs,
   resolvers,
   context: async ({ req }) => {
      let authToken = null;
      let currentUser = null;

       try {
          authToken = req.headers[HEADER_NAME];

          if (authToken) {
               currentUser = await tradeTokenForUser(authToken);
          }
       } catch (e) {
          console.warn(`Unable to authenticate using auth token: ${authToken}`);
       }

      return {
          authToken,
          currentUser,
      };
   },
});

server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});
export const authenticated = next => (root, args, context, info) => {
  if (!context.currentUser) {
      throw new Error(`Unauthenticated!`);
  }

  return next(root, args, context, info);
};

我不明白“下一个”参数的作用以及为什么在调用此防护时作为参数我必须返回一个值?

最佳答案

authenticated 是使代码干燥的高阶函数。 next 是用作谓词的回调。

这是一种更干燥的写作方式:

...
me: (root, args, context) => {
  if (!context.currentUser) {
      throw new Error(`Unauthenticated!`);
  }

  return context.currentUser;
)
...

关于javascript - 如何在 graphql 解析器中实现守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56087652/

相关文章:

javascript - Angular4 和 Webpack - 300kb(优化后)用于简单的 "hello world"应用程序?

javascript - ie8_getElementById()

node.js - 使用 async/await 尝试/捕获 block

reactjs - `componentDidMount` 到底是什么时候被触发的?

javascript - Reactjs 错误 : Uncaught (in promise) Error: Request failed with status code 401

javascript - TypeError : is not a function. 绑定(bind)此的正确方法。 JS 中的引用

javascript - 在 NodeJS 中根据内容长度查找视频时长

node.js - 创建后 Postgresql 数据库在 travis ci 中不存在

node.js - 如何使用 angularjs 和 nodejs 处理浏览器缓存?

javascript - react-bootstrap-table-toolkit 搜索导入报错