PatchString

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

No mapper:

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

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

const updatedData = JSON.parse(example.data);

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

await this.examplesRepository.update(
  {
    ...example,
    data: JSON.stringify(updatedData),
  },
  trx,
);

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

Using mapper:

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

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

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

await this.examplesRepository.update(
  {
    ...example,
    data: patchString(example.data, inputData),
  },
  trx,
);

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