我试图根据能力规则限制我的查询范围,尤其是倒置规则。
使用助手,rulesToQuery
它似乎无法处理反转。至少,不像我预期的那样。在构建对象时rulesToQuery
,似乎使用rule.inverted
属性来确定$and
或$or
条件;const op = rule.inverted ? '$and' : '$or';
这感觉不对。
我用错了吗?有没有其他人解决过这个问题?
const { interpret } = require('@ucast/sql/objection');
const { CompoundCondition } = require('@ucast/core');
cnost { AbilityBuilder, Ability } = require('@casl/ability');
const { can, cannot, build } = new AbilityBuilder(Ability);
const { rulesToQuery } = require('@casl/ability/extra');
// this ability should be able to see all stores except store with id 5
can('read', 'Store', { id: { $exists: true }});
cannot('read', 'Store', { id: 5 });
function toObjectionQuery(ability, action, query) {
const rules = rulesToQuery(ability, action, 'Store', (rule) => {
if (!rule.ast) {
throw new Error('Unable to create Objection.Query without AST');
}
return rule.ast;
});
const { $and = [], $or = [] } = rules;
const condition = new CompoundCondition('and', [...$and, new CompoundCondition('or', $or)]);
return interpret(condition, query);
}
更新:
为了解决缺乏否定相等的问题,我必须更改解释器的运算符。
function toObjectionQuery(ability, action, query) {
const rules = rulesToQuery(ability, action, 'Store', (rule) => {
if (!rule.ast) {
throw new Error('Unable to create Objection.Query without AST');
}
let ast = {...rule.ast};
if (rule.inverted) {
ast.operator = 'ne';
}
return ast;
});
const { $and = [], $or = [] } = rules;
const condition = new CompoundCondition('and', [...$and, new CompoundCondition('or', $or)]);
return interpret(condition, query);
}
目前,这将在不同类型的运算符上中断,而不是eq
.
更新 2:也许,我从stalniy
's gist 偷来的例子是不正确的。实现此目的的另一种方法是使用“非”构建 CompoundCondition。
function toObjectionQuery(ability, action, query) {
const rules = rulesToQuery(ability, action, 'Store', (rule) => {
if (!rule.ast) {
throw new Error('Unable to create Objection.Query without AST');
}
let ast = {...rule.ast};
return ast;
});
const { $and = [], $or = [] } = rules;
const condition = new CompoundCondition('and', [new CompoundCondition('or', $or), new CompoundCondition('not', new CompoundCondition('or', $and)])]);
return interpret(condition, query);
}
我相信这将否定整个倒置从句。