我试图将对某些属性的访问权限限制为仅限在深层嵌套接口(interface)中的组中具有该属性的用户,并且我无法访问嵌套组件中的“组”元数据。
这是一个代码示例:
响应示例:
export class ProductResponseInterface {
// groups work fine here
@ValidateNested()
success: boolean;
@Type(() => ProductFetchResponseInterface)
data?: ProductFetchResponseInterface;
error?: string;
@Exclude()
groups?: string[];
constructor(partial: Partial<ProductResponseInterface>) {
Object.assign(this, partial);
}
}
export class ProductFetchResponseInterface {
// groups seem to be undefined here
@ValidateNested()
@Type(() => ProductInterface)
@Expose({ groups: ['eshop.products'] })
products: ProductInterface[];
@Exclude()
groups: string[];
count: number;
constructor(partial: Partial<ProductFetchResponseInterface>) {
Object.assign(this, partial);
}
}
export class ProductInterface {
// groups seems to be undefined here
@Expose({ groups: ['eshop.products.product.id', 'admin'] })
id: number;
@Expose({ groups: ['eshop.products.product.name'] })
name: string;
...
constructor(partial: Partial<ProductInterface>) {
Object.assign(this, partial);
}
}
问题: ProductFetchResponseInterface 和 ProductInterface 无权访问“groups”标记,并且它们的响应返回空产品。
这是使用这些接口(interface)的调用
const http_response = await this.handle_request(url);
// { success: true, data: { products: [ { id: 1, name: 'product_name' }]}}
return plainToInstance(
ProductResponseInterface,
{
...response,
groups: user.access_permissions_populated // ['eshop.products', 'eshop.products.product.id',...],
},
{},
);
关于如何让它发挥作用有什么想法吗? 谢谢。
最佳答案
您需要像这样调用 plainToInsatnce
plainToInstance(ProductResponseInterface, plainObject, { groups: ["eshop.products", "eshop.products.product.name", "eshop.products.product.id"] })
有测试示例
import "reflect-metadata";
import { plainToInstance } from "class-transformer"
import { ProductResponseInterface } from "./test"
describe("", () => {
it("tranform items by groups attribute", () => {
const raw = { success: true, data: { products: [{ id: 1, name: 'product_name' }] } }
const res = plainToInstance(ProductResponseInterface, raw, { groups: ["eshop.products", "eshop.products.product.name", "eshop.products.product.id"] })
const exp: ProductResponseInterface = {
success: true,
data: {
products: [
{
id: 1,
name: "product_name"
}
],
groups: undefined,
count: undefined,
}
}
expect(res).toEqual(exp);
});
});
关于javascript - 如何在嵌套组件中使用 "groups"访问 "class-transformer",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73373836/