2

when I want to send information as post Method to my Rest API, Angular sends empty fields and subsequently, my database saves the empty value.

But I want to prevent it and I don't want to send empty fields from my Angular to my Backends.

For example, in below example, Angular sends an "" in entityTypeName field and unfortunately, the Postgres DB will save empty instead of null.

{ 
   createdAt: "2019-01-11T13:59:52.311678"
   entityTypeName: ""
   id: "1bd46fce-fc6f-410f-acaf-74d5964cf92b"
   updatedAt: "2019-01-11T13:59:52.311678"
   updatedBy: "admin@admin.com"
   version: 0 
}

I'm looking for a general solution that prevent sending empity values in Angular side in all situations.

HadiMohammadi
  • 133
  • 3
  • 8
  • There isn't a general solution. You either make sure that client is sending valid requests, validate them on the backend before acting on them, or (ideally) both. You need a rule somewhere that says that `""` is not a valid value for `entityTypeName`. – jonrsharpe Jan 11 '19 at 13:40
  • Thanks, but so sad. – HadiMohammadi Jan 11 '19 at 13:42

2 Answers2

5

Here is a function doing it. Simply provide your object to the function, and it will delete the empty keys.

function removeEmptyStringsFrom(obj) {
  const clone = { ...obj };
  Object.entries(clone).forEach(([key, val]) => val === '' && delete clone[key]);
  return clone;
}

const test = {
  notEmpty: 'toto',
  empty: '',
};

console.log(removeEmptyStringsFrom(test));

EDIT : Challenge accepted !

const removeEmptyStringsFrom = (obj) => Object
  .entries({ ...obj })
  .filter(([key, val]) => val !== '')
  .reduce((prev, curr) => ({ ...prev, [curr[0]]: curr[1] }), {});

const test = {
  notEmpty: 'toto',
  empty: '',
};
    
console.log(removeEmptyStringsFrom(test));
0

Since you do not provide any kind of example i am going to base my answer on the assumptions that you pass an instance of an object (lets name it entity) in the body and you let the HttpClient handle the serialisation to json.

If you want to get rid of properties with the empty string you could delete the property

delete entity.entityTypeName

For a generic solution that would remove all empty string properties, you could use an HttpInterceptor that would

  • check if the outgoing httpRequest holds a json body
  • iterate through all the properties (or specific properties)
  • delete those that are declared as empty strings
Nikos Tsokos
  • 3,226
  • 2
  • 34
  • 41