For the front-end of a web application I am building, I am using a RESTful web service to fetch my data. Such a call and response could look like the following:
// GET http://ift.tt/2qMLgHf
{
p_id: 3,
p_fn: 'Jon',
p_ln: 'Smith',
p_addr: {
str: 'Baker Street',
city: 'London',
cntry: 'GB'
},
// and more stuff...
}
I don't need all of this data in my application, so I decided to map them into my own class. This also gives the benefit of renaming and restructuring the properties, decoupling from the external API, and the ability to add some methods:
class Person {
name: {
first: string,
last: string
};
country: string;
getFullName(): string {
return this.name.first + ' ' + this.name.last;
}
}
This example uses TypeScript, but could also be created using ES6 classes
This works fine until I want to change the properties of this object.
For example the Person
s country must be changed, because he moved to France. And also his name is edited, because there was an error:
person.country = 'FR'
person.name.first = 'John'
Now the changes must be sent back to the external service:
// UPDATE http://ift.tt/2qMLgHf
{
p_id: 3,
p_fn: 'John',
p_ln: 'Smith',
p_addr: {
str: 'Baker Street',
city: 'London',
cntry: 'FR' // This is where my example falls apart
},
// and more stuff...
}
But if no property was changed, the call must not be executed at all, so there must be some kind of detection for that.
So basically I constantly have to translate back and forth between these local instances and DTO-like objects. What would be the best way to set this up?
Is there any standard way of doing this? I heard some stuff about ORM or persistence patterns, but is any of this applicable to JavaScript? Are there best practices for doing this client-side?
Aucun commentaire:
Enregistrer un commentaire