node.js - 我如何存取 CASL 條件的巢狀屬性
我似乎無法使用條件規則訪問嵌套對象。我希望用戶能夠刪除文章,如果該文章的評論ID與用戶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[]' 中不存在』
答案#1
你可以在 https://casl.js.org/v5/en/advanced/typescript 上找到「使用點記法的嵌套欄位」部分,這會很有用。簡而言之,當你在 TypeScript 中使用點記法來定義條件時,你需要創建一個自訂類型:
type FlatArticle = Article & {
'comment.id': Article['comment']['id']
};
can<FlatArticle>('read', Article, { 'comment.id': 1 });
答案#2
最後是這樣解決的:
export enum Action {
Manage = 'manage',
Create = 'create',
Read = 'read',
Update = 'update',
Delete = 'delete',
}
export type Subject = InferSubjects<typeof Article |
typeof Comment |
typeof User |
'all';
export type AppAbility = PureAbility<[Action, Subject]>;
export const AppAbility = Ability as AbilityClass<AppAbility>;
然後像這樣定義規則:
createForUser(user: User) {
const { can, cannot, build } = new AbilityBuilder(AppAbility);
can(Action.Read, Article, { 'comment.id': 1 });
return build({
detectSubjectType: item => item.constructor as ExtractSubjectType<Subject>
});
}
