我在模式拼接中使用阿波罗链接作为访问控制层。如果用户没有访问特定操作的权限,我不太确定如何做出链接返回错误响应。我知道像graphql-shield和graphql-middleware这样的软件包,但是我很好奇是否可以使用阿波罗链接来实现基本的访问控制。
下面是我的链接:
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 }));middlewareLink有根据用户角色返回true of false的checkPermissions
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是false,我该怎么办?我想我不需要转发操作,因为现在很明显,用户没有访问它的权限
更新
我想我需要做的是扩展ApolloLink类,但是到目前为止我还没有返回错误
发布于 2018-09-25 12:59:02
经过一番挖掘,我终于弄明白了。但我不太确定我的方法是否正确。
基本上,我使用后续的forward调用map,其中返回一个包含errors和data字段的对象。同样,我想还有一种更好的方法(也许通过扩展ApolloLink类)
const middlewareLink = new ApolloLink((operation, forward) => {
const { operationName } = operation;
if (operationName !== 'IntrospectionQuery') {
const { variables } = operation;
const context = operation.getContext().graphqlContext;
try {
checkPermissions({ operationName, context, variables });
} catch (err) {
return forward(operation).map(() => {
const error = new ForbiddenError('Access denied');
return { errors: [error], data: null };
});
}
}
return forward(operation);
});发布于 2022-02-01 07:38:24
不知道是否还有其他人需要这样做,但我试图在onError回调中使用类型记录和响应来获得一个特定的onError。终于做到了这一点:
const testLink = new ApolloLink((operation, forward) => {
let fetchResult: FetchResult = {
errors: [] // put GraphQL errors here
}
let linkResult = Observable.of(fetchResult).map(_ => {
throw new Error('This is a network error in ApolloClient'); // throw Network errors here
});
return linkResult;
});在可观察的GraphQL响应中返回FetchResult错误,而在可观察回调中抛出错误将生成NetworkError
https://stackoverflow.com/questions/52497957
复制相似问题