2

Simple question but I would like to know how to do this effectively. Very prone to attract negative votes.

I have a model which I want to share between front-end and back-end. For front-end manually I want to add few attributes. These attributes are not required for back end.

export class ModelA {
id: string;
name: string;
value: number;
}

above is sufficient for server (back-end).

But in front end I need to do one extra thing.Based on value I need to define color attribute (value < 10, color green etc..)

export class ModelA {
id: string;
name: string;
value: number;
color: string;
}

So when I'm updating ModelA back to the server after editing id/name whatever I don't want to pass color attribute.

With single model how could I achieve this?

Pratap A.K
  • 4,337
  • 11
  • 42
  • 79

1 Answers1

2

I think what you are looking for in this case is slicing (see for example this : How to get a subset of a javascript object's properties )

You are effectively taking a subset of the properties of your object,

let objectFront = { id: 'a', name: 'b', value: 'c', color: "d" };
let objectBack = (({id, name, value}) => ({id, name, value}))(objectFront);

EDIT: Also, I am not sure how having more properties on your object is bad for you. It depends on your framework and your method of query. I would just go for simply ignoring the additional properties of my object when receiving it on back-end part.

Pac0
  • 21,465
  • 8
  • 65
  • 74
  • My scenario is slightly different. I'll get ModelA from server and I want to add 1 extra attribute to it. While updating back to the server I don't need to pass the extra added attribute. Extra added attribute is only required with in front end. – Pratap A.K May 30 '17 at 09:09
  • Having more unnecessary property is bad because we are sending more data to back-end. – Pratap A.K May 30 '17 at 09:14
  • Then, I don't see how you can achieve this with a single model. You have modelA, the real data model from your server, and modelB is what I would call a ViewModel (not sure if it 's the right term here). I would make the "transtyping" in the service who is responsible for sending your object. – Pac0 May 30 '17 at 09:19
  • yea, currently I'm using 2 models. Just wondering whether we can achieve with single model or not. – Pratap A.K May 30 '17 at 09:21
  • 1
    What you could, but I don't know if it is applicable in your case, Is completely separate the color property from the model. Use a wrapper object that contains your `modelA ` object as first property and 'color' information as second property. When you do your request, you just send wrapper.modelA and not the whole object wrapper. – Pac0 May 30 '17 at 09:22
  • 1
    Indeed this works. I can add attributes when needed and can slice it when not required. Only thing is those extra attributes which I need in front-end must to be optional property. color?:string; thanks for the help!! cheers – Pratap A.K May 30 '17 at 10:03