假设我有以下 Ember 数据模型:
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
starred: DS.attr('boolean')
});
这通过以下非常标准的 CRUD API 与 Rails 应用程序通信:
GET /people - get a list of people
POST /people - create a new person
GET /people/id - get a specific person
PUT /people/id - update a specific person
DELETE /people/id - delete a specific person
这一切都映射到带有标准存储/适配器的 Ember-Data。
但是,假设为了给某人“加注星标”或“取消加注星标”,API 不允许我们通过标准更新操作执行此操作。此操作有一个特定的 API 端点:
POST /people/id/star - mark a person as "starred"
POST /people/id/unstar - mark a person as "unstarred"
如何将此 API 与 Ember 数据相匹配?
看起来我需要以某种方式扩展 DS.Store 和 DS.RESTAdapter,但我不确定让它们了解这些不同操作的最佳方法。应用程序的通用适配器必须知道主演人物,这也让人感觉有点不对。
请注意,我无法控制 API,因此我无法让 POST/people/id
知道“starring”,以便它适合标准更新。
最佳答案
有一段时间了,当时可能还不行,但是你可以直接调用你适配器的ajax方法:
YourApp.Store.prototype.adapter.ajax(url, action, {data: hashOfParams})
例如:
YourApp.Store.prototype.adapter.ajax('/products', 'GET', {data: {ids: [1,2,3]}})
针对您的问题:
YourApp.Store.prototype.adapter.ajax('/people' + id + '/star','POST')
编辑 - 使用 buildURL 很有用,尤其是当您在适配器上设置了 namespace 时:
url = YourApp.Store.prototype.adapter.buildURL('people',id) + '/star'
编辑 2 - 您还可以使用 container.lookup('adapter:application')
获取适配器,如果您没有全局访问权限,这将很有用应用程序(前 ES6 模块/ember-cli)
编辑 3 - 以上是指 Ember/Ember-CLI 的过时版本。现在我在 mixin 中定义这个函数 -
customAjax: (method, type, id, action, hash = null) ->
#note that you can now also get the adapter from the store -
#adapter = @store.adapterFor('application')
adapter = @container.lookup('adapter:application')
url = adapter.buildURL(type, id) + '/' + action
hash['data'] = $.extend({}, hash) if hash #because rails
adapter.ajax(url, method, hash).then (result) =>
return result
然后这样调用它-
@customAjax('PUT', 'modelClass', modelId, 'nonCRUDActionName', optionalHashOfAdditionalData).then (response) =>
#do something with response
关于javascript - 使用 ember-data 的非 CRUD 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9705773/