PatchAttribute

Takes as parameter an entity and an object, maps the object, and returns the entity with the patched properties. Empty or non-entity-type properties are discarded.

No mapper:

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

Using mapper:

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", // It also prevents against non-related inputs
  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,
};