Authorization in graphql resolvers as middleware

时间:2019-05-31 11:23:37

标签: node.js graphql decorator apollo-server

I need to check is user authorized to do this or to do that in resolvers, but i don't want to write same codes in every resolvers. So it seems i should use decorators. But i don't know how to use decorators there without classes.

the decoded UserId from jwt token is there i req object with using context, and my resolver like this:

import { isAllowed } from 'somewhere';
export default {
  Query: {
    async q1(_, args, {req}) {
      if (!isAllowed(req.userId,'action') throw new Error('Not Authorized!');
    },
  ...
}

I've something like this in my mind:

export default {
  Query: {
    @isAllowed
    async q1(_, args, {req}) {
      // ...
    },

    // this method doesn't need authorization.
    async q2(_,args, {req}) {

    }
}```

But i don't know how to implement it.

1 个答案:

答案 0 :(得分:0)

我发现我应该使用double*来处理授权,而不是解析器方法修饰。