簡體   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