繁体   English   中英

如何在嵌套组件中使用“类转换器”访问“组”

[英]How to access "groups" using "class-transformer" in nested components

我试图将访问某些属性的权限仅限于在深度嵌套界面中的组中具有该属性的用户,并且我无法访问嵌套组件中的“组”元数据。

这是一个代码示例:

响应示例:

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 无权访问“组”标签,并且它们的响应返回空产品。

这是使用这些接口的调用

    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);
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM