PatchAttribute

Toma como parâmetro uma entidade e um objeto, mapeia o objeto e retorna a entidade com as propriedades corrigidas. Propriedades vazias ou desconexas são descartadas.

Sem mapeador:

const example: Example = {
  name: "example",
  description: "this is an example",
  extra: undefined,
  size: "123",
  price: 100,
};

const inputData: IExampleDTO = {
  name: undefined,
  description: "this is a new description",
  extra: "this is an extra",
  size: undefined,
  price: 20,
};

if (inputData.name) {
  example.name = inputData.name;
}
if (inputData.description) {
  example.description = inputData.description;
}
if (inputData.extra) {
  example.extra = inputData.extra;
}
if (inputData.size) {
  example.size = inputData.size;
}
if (inputData.price) {
  example.price = inputData.price;
}

await this.examplesRepository.update(example, trx);

output = {
  name: "example",
  description: "this is a new description",
  extra: "this is an extra",
  size: "123",
  price: 20,
};

Usando mapeador:

import { patchAttribute } from "@utils/mappers";

const example: Example = {
  name: "example",
  description: "this is an example",
  extra: undefined,
  size: "123",
  price: 100,
};

const inputData: IExampleDTO = {
  name: undefined,
  description: "this is a new description",
  extra: "this is an extra",
  size: undefined,
  price: 20,
  nonEntityFieldSent_1: "1", // Também previne contra dados não relacionados
  nonEntityFieldSent_2: "2",
  nonEntityFieldSent_3: "3",
  nonEntityFieldSent_4: "4",
};

await this.examplesRepository.update(
  patchAttribute(example, inputData),
  trx,
);

output = {
  name: "example",
  description: "this is a new description",
  extra: "this is an extra",
  size: "123",
  price: 20,
};