简体   繁体   English

JavaScript从外部REST API映射JSON数据

[英]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. 对于我正在构建的Web应用程序的前端,我正在使用RESTful Web服务来获取数据。 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: 这还带来了以下优点:重命名和重组属性,与外部API分离,以及添加一些方法的能力:

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 本示例使用TypeScript,但也可以使用ES6类创建

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. 例如,该Person的国家必须更改,因为他移居法国。 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. 因此,基本上,我经常不得不在这些本地实例和类似DTO的对象之间来回转换。 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? 我听说过一些有关ORM或持久性模式的内容,但是其中任何一种适用于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. 如果要发回数据,并且它是UPDATE而不是PATCH,则您的类应包含更新资源所需的所有属性。

How about creating a constructor method for your class where you pass in the JSON? 如何为您传递JSON的类创建构造函数方法 And a toJSON class-method where you parse the properties into correctly formatted JSON. 还有toJSON类方法,您可以在其中将属性解析为格式正确的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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