简体   繁体   中英

JavaScript mapping JSON data from external REST API

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 api.example.com/persons/3
{
    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:

// PUT api.example.com/persons/3
{
    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?

If you're sending the data back and it's an UPDATE and not a PATCH, your class should contain all the properties needed to update the resource.

How about creating a constructor method for your class where you pass in the JSON? And a toJSON class-method where you parse the properties into correctly formatted JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM