如何从解析器访问GraphQL中的上下文

时间:2019-07-10 11:46:56

标签: graphql express-graphql

我只想通过上下文字段将请求发送给所有解析器,但是当我从一个解析器访问它时,它返回null。

app.use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => ({
  schema: schema,
  context:{token_1:null,test:request},
  graphiql:true
})));

这些是我的架构的一部分。首先,我登录以设置令牌,但是当我想从另一个解析器(BuyItems)访问context.token_1时,它将返回null。

  BuyItems :{
      type: UserType,
      args: {
        name: {type: GraphQLString},
        points: {type: GraphQLInt}
      },
      resolve(parent,args,context){
        console.log(context.token_1)
        return UserModel.findOneAndUpdate({name:args.name},{points:args.points})
      }
  },
  Login: {
      type: AuthType,
      args: {
        email: {type:GraphQLString},
        password: {type:GraphQLString}
      },
      async resolve(parent,args,context){
        const user = await UserModel.findOne({ email: args.email });
        if (!user) {
          throw new Error('User does not exist on login!');
        }
        const isEqual = await bcrypt.compare(args.password, user.password);
        if (!isEqual) {
          throw new Error('Password is incorrect!');
        }
        const token = jwt.sign(
          { userId: user.id, email: user.email },
          'somesupersecretkey',
          { expiresIn: '1h' }
        );
        context.token_1 = token;
        return {tokenExpiration: 1, userId: user.id, token:token}
    }
  }

0 个答案:

没有答案