我似乎无法使用条件规则访问嵌套对象。如果文章的评论与用户具有相同的 ID,我希望用户有权删除文章。这些只是一些编造的课程来测试......
这是我的代码:
import { defineAbility, AbilityBuilder } from '@casl/ability';
import { Ability, AbilityClass, ExtractSubjectType, InferSubjects } from '@casl/ability';
export class Article {
static readonly modelName = "Article";
static readonly __typename = "Article";
constructor( id: number,
title: string,
content: string,
user: User,
comment: Comment) {
this.id = id
this.title = title
this.content = content
this.user = user
this.comment = comment
}
id: number
title: string
content: string
user: User
comment: Comment
}
export class User {
static readonly modelName = "User"
static readonly __typename = "User";
constructor (id: number,
name: string,
comment: Comment) {
this.id = id
this.name = name
this.comment = comment
}
id: number
name: string
comment: Comment
}
export class Comment {
static readonly modelName = "Comment"
static readonly __typename = "Comment";
constructor(id: number,
content: string,
authorId: number) {
this.id = id
this.content = content
this.authorId = authorId
}
id: number
content: string
authorId: number
}
type Action = 'create' | 'read' | 'update' | 'delete';
type Subjects = InferSubjects<typeof Article | typeof Comment| typeof User, true>;
export type AppAbility = Ability<[Action, Subjects]>;
export function createForUser(user: User) {
const { can, cannot, build } = new AbilityBuilder<
Ability<[Action, Subjects]>
>(Ability as AbilityClass<AppAbility>);
can('delete', Article, { comment: {id: user.comment.id}})
return build({
detectSubjectType: item => item.constructor as ExtractSubjectType<Subjects>
});
}
并通过以下方式对其进行测试:
const comment = new Comment(0, 'a', 0)
const user = new User(1, 'sd', comment);
const article = new Article(2, 'sd', 'asd', user, comment)
const ability = createForUser(user);
console.log(ability.can('delete', article))// false
我在某处看到我需要做这样的事情:
can('delete', Article, { 'comment.id': user.comment.id})
但是当我这样做时说'对象文字可能只指定已知属性,而''comment.id''在'string []'类型中不存在