RESTful JSON API 需要的约定才能与 Ember 一起使用 [英] Conventions required of RESTful JSON API to be usable with Ember

查看:23
本文介绍了RESTful JSON API 需要的约定才能与 Ember 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ember 模型介绍中提到:

In the Ember Models Introduction, it is mentioned:

无需任何配置,Ember Data 就可以加载和保存记录和他们的关系通过 RESTful JSON API 提供服务,前提是它遵循某些约定.

Without any configuration, Ember Data can load and save records and their relationships served via a RESTful JSON API, provided it follows certain conventions.

我开始尝试使用基于令牌的 RESTful JSON API,乍一看,这并不是严格的 RESTful.几个例子:

I'm getting started trying to use a token based, RESTful JSON API, which at first glance is not strictly RESTful. Few examples:

  1. 身份验证实现为 GET /api/authenticate?email=a@b.com&password=pass
  2. 大多数 API 的返回状态为 200(响应标头),即使在失败时也是如此.返回的 json 包含附加字段 success (boolean) 和 code (int),指示 API 是失败还是通过.
  3. 网址不基于名词(模型).例如,一个典型的消息编辑操作通常应该是对像 /api/message/1/edit 这样的 url 的 POST 实现为 GET /api/edit_message?id=1&text=新
  1. Authentication is implemented as GET /api/authenticate?email=a@b.com&password=pass
  2. Most of the API's return Status of 200 (response header) even on failure. The returned json contains additional fields success (boolean) and code (int) which indicate if the API failed or passed.
  3. The urls are not based on nouns (models). For example, a typical message edit operation which should conventionally be a POST to a url like /api/message/1/edit is implemented as GET /api/edit_message?id=1&text=new

所以,我想知道是否有人可以列出文档中提到的这些某些约定.这可以帮助我了解是否可以使用 ember-data.

So, I was wondering if someone could list what these certain conventions are that are mentioned in the docs. This could help me understand if I could use ember-data or not.

推荐答案

简短的回答是 EmberData 可能不适合您的 REST API,因为您的 REST API 并不是真正的 REST API(它不使用HTTP 动词,而是将操作作为查询字符串的一部分嵌入).

The short answer is that EmberData is probably not a good fit for your REST API as your REST API isn't really a rest API (it doesn't use HTTP verbs and instead embeds actions as part of the query string).

为什么 Ember 数据可能不适合您

虽然过去 Ember Data 项目的目标可能是支持您所描述的 API,但最近,Ember Data 开发人员明确表示他们不打算让 Ember Data与非常规 API 一起使用.例如,旨在弥合差距"并允许将 Ember 数据与非常规 REST API 一起使用的 BasicAdapter 已被删除.

While it may have been a goal of the Ember Data project in the past to support an API such as the one you are describing, more recently, the Ember Data developers have explicitly stated that they do not intend for Ember Data to be used with non-conventional APIs. For example, the BasicAdapter which was meant to "bridge the gap" and allow the use of Ember data with non-conventional REST APIs has been removed.

这是 Emberjs.com 上博客文章的实际引用和链接(值得一读):

Here's the actual quote and link to the blog post at Emberjs.com (worth a read):

Ember Data 现在将专注于成为最好的图书馆Ember.js 应用程序与一致的传统 API 进行通信."(http://emberjs.com/blog/2013/05/03/ember-data-progress-update.html)

"Ember Data will now focus on being the best possible library for Ember.js apps to communicate with consistent, conventional APIs." (http://emberjs.com/blog/2013/05/03/ember-data-progress-update.html)

按照该博文中的建议,您应该查看以下可能更适合您情况的数据持久性库:

As recommended in that blog post you should check out the following data persistence libraries which might be better suited to your situation:

https://github.com/endlessinc/ember-restless

https://github.com/ebryn/ember-model

最后,你总是可以像 Discourse 的人那样用 AJAX 自己做http://eviltrout.com/2013/03/23/ember-without-data.html

Finally, you can always do it yourself with AJAX much like the Discourse folks did http://eviltrout.com/2013/03/23/ember-without-data.html

身份验证

据我所知 Ember Data 不处理应用程序身份验证,这就是我认为您在那里的示例所得到的.对于您的身份验证系统,您可以查看 Ember.SimpleAuth (https://github.com/simplabs/ember-simple-auth),这是高度可配置的,应该与您的身份验证机制配合使用(尽管它肯定需要编写自定义身份验证器).

As far as I know Ember Data does not handle application authentication which is what I think you're getting at with your example there. For your authentication system you could look at something like Ember.SimpleAuth (https://github.com/simplabs/ember-simple-auth) which is highly configurable and should work with your authentication mechanism (although it will definitely require writing a custom Authenticator).

编写自定义身份验证器非常简单.

Writing a custom Authenticator is pretty straightforward.

实际期望的 Ember 数据是什么

如果您还没有看过此页面,我建议您阅读一下:http://emberjs.com/guides/models/the-rest-adapter/

I'd recommend reading over this page if you haven't seen it yet: http://emberjs.com/guides/models/the-rest-adapter/

Ember Data 将使用 HTTP 动词来传达意图.因此,当您在其中一个模型上调用 createRecord 并保存存储时,Ember Data 将向您的 REST API 发出 HTTP POST.当您尝试获取记录时,Ember 将发出 GET 请求.当您尝试删除记录时,Ember 将发出 DELETE 请求(等等).

Ember Data is going to use HTTP Verbs to convey intent. So when you make a call to createRecord on one of your models and then save the store, Ember Data will issue an HTTP POST to your REST API. When you try to get a record, Ember will issue a GET request. When you try to delete a record Ember will issue a DELETE request (etc. etc.).

假设您有三个看起来像这样的模型:

Lets say you have three models that looks like this:

module.exports = App.ShoppingCart = DS.Model.extend({
    user: DS.belongsTo('user'), 
    items: DS.hasMany('item', {async:true}),
    name: attr('string'),
    enabled: attr('boolean')
});

module.exports = App.Item = DS.Model.extend({
    name: attr('string')
});

module.exports = App.User = DS.Model.extend({
   firstName: attr('string')
   lastName: attr('string')
});

当您尝试使用 this.store.find('shoppingCart', 1) 加载记录时,Ember 将向模型名称的复数形式发出 GET 请求(在本例中为 获取/shoppingCarts/1).Ember 内置了一堆规则来确定单词的复数形式,例如它知道 search 的复数形式是 searches 而不是 searchs.发出 GET 请求后,您的 REST API 需要返回以下 JSON:

When you attempt to load a record using this.store.find('shoppingCart', 1) Ember will make a GET request to the pluralized form of the model name (in this case GET /shoppingCarts/1). Ember has a bunch of rules built in to determine the plural form of a word so for example it knows that the plural of search is searches and not searchs. Once the GET request is made your REST API needs to return the following JSON:

{
  "shoppingCart": {
      "id": 1,
      "name": "Bobs Shopping Cart",
      "user": 1, //this field links to the user with an id of 1
      "enabled": true,
      "items": [
        1,
        2
      ] 
    }
}

如果你在做 this.store.find('shoppingCart') 那么 Ember Data 将发出一个 GET/shoppingCarts 并期望返回一组键控的购物车对象与模型名称的复数形式.例如,像这样:

If you were doing this.store.find('shoppingCart') then Ember Data will issue a GET /shoppingCarts and expect back an array of shopping cart objects keyed with the plural form of the model name. For example, like this:

{
  "shoppingCarts": [
     {
       "id": 1, //not specified in the model but must be sent by the REST API
       "name": "Bob's Shopping Cart",
       "user": 1, //this field links to the user with an id of 1
       "enabled": true,
       "items": [
         1,
         2
       ] 
     },
     {
       "id": 2, 
       "name": "John's Shopping Cart",
       "user": 2, //this field links to the user with an id of 2
       "enabled": false,
       "items": [
         3,  // these are ids for the item models
         4
       ] 
     }
  ]
}

请注意,当您从服务器返回记录时,您需要包含一个 id 字段,该字段唯一标识正在返回的记录.模型本身未指定 id 字段.当您创建新记录并将数据发送到服务器时,您不包括 id 字段(因为它将由服务器端确定),但 REST API 将需要返回响应中的 id.

Note that when you return records from the server you need to include an id field which uniquely identifies the record being returned. The id field is not specified in the model itself. When you create a new record and send data to the server you don't include the id field (as it will be determined server side) but the REST API would then need to return what the id is in the response.

在上面的例子中,如果 Ember Data 在商店中缓存了用户1",那么它只会使用该信息,否则它将向 GET/users/1 发出另一个 GET 请求以检索用户 1 的信息.(如果您想避免多个 GET 请求,您可以通过旁加载记录来提高效率).

In the example above, if Ember Data has user "1" cached in the store then it will just use that information, otherwise it will make another GET request to to GET /users/1 to retrieve information for user 1. (You can make this more efficient by sideloading records if you want to avoid multiple GET requests).

总而言之,约定是使用 HTTP 动词来传达应该采取什么操作,Ember Data 将请求发送到的 URL 是基于您正在查询的模型名称的复数形式.

To sum up, the convention is to use HTTP verbs to convey what action should be taken, the URL that Ember Data will send the request to is based on the pluralized form of the model name that you are querying.

重要警告

我上面写的大部分内容都是基于这样一个假设,即您希望开箱即用"地使用 Ember Data,而无需进行过多的定制.一般来说,我认为当您可以控制 REST API 并且可以调整它以符合 Ember Data 关于基于 JSON 的 REST API 应该如何工作的意见时,Ember Data 最容易使用.可以更改 Ember Data 的默认行为,但我对尝试弯曲 Ember Data 以适应我的 API 的经验不是很丰富,因此您可能需要尝试这样做的其他人的一些输入.

Most of what I wrote above is based on the assumption that you want to use Ember Data "out of the box" without too much customization. Generally speaking I think Ember Data is easiest to work with when you have control over the REST API and can adjust it to conform to Ember Data's opinion of how a JSON based REST API should work. It is possible to change the default behavior of Ember Data but I'm not very experienced with trying to bend Ember Data to fit my API so you might need some input from someone else that has tried to do this.

这篇关于RESTful JSON API 需要的约定才能与 Ember 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆