我在模式拼接中使用阿波罗链接作为访问控制层。我不太确定如果用户没有访问特定操作的权限,如何使链接返回错误响应。我知道这样的包graphql-shield
and graphql-middleware
但我很好奇是否可以使用 apollo link 实现基本的访问控制。
我的链接如下所示:
const link = setContext((request, previousContext) => merge({
headers: {
...headers,
context: `${JSON.stringify(previousContext.graphqlContext ? _.omit(previousContext.graphqlContext, ['logger', 'models']) : {})}`,
},
})).concat(middlewareLink).concat(new HttpLink({ uri, fetch }));
The middlewareLink
has checkPermissions
返回true
of false
取决于用户的角色
const middlewareLink = new ApolloLink((operation, forward) => {
const { operationName } = operation;
if (operationName !== 'IntrospectionQuery') {
const { variables } = operation;
const context = operation.getContext().graphqlContext;
const hasAccess = checkPermissions({ operationName, context, variables });
if (!hasAccess) {
// ...
}
}
return forward(operation);
});
如果我该怎么办hasAccess
is false
。我想我不需要转发该操作,因为此时很明显用户无权访问它
UPDATE
我想我需要做的是延长ApolloLink
类,但到目前为止我还没有设法返回错误