【发布时间】:2015-06-23 19:34:36
【问题描述】:
我正在尝试使用 ember-data 通过 id 和查询参数向端点发送请求。 ajax 调用的最终输出将是http://api.example.com/invoices/1?key=value。据我所知,ember-data 的store 没有通过 id 和查询参数查找的本地方式(以下都不起作用):
// outputs http://api.example/com/invoices/1
this.store.find('invoice', 1);
// outputs http://api.example.com/invoices?id=1&key=value
this.store.find('invoice, {id: 1, key: value});
相反,我一直在尝试修改发票适配器。我们的后端是 Django,所以我们使用ActiveModelAdapter。我想重写构建 url 的方法,以便如果 id 存在于 query 对象中,它将自动将其删除并将其附加到 url,而不是在将 query 对象的其余部分转换为 url 参数之前.
唯一的问题是我不知道要覆盖哪个方法。我查看了ActiveModelAdapterhere 的文档,并尝试覆盖findRecord、buildUrl、urlForFind 和urlForQuery 方法,但由于某种原因,它们都没有被调用(我尝试过通过console.log 和Ember.debug 登录)。我知道适配器工作正常,因为namespace 工作正常。
这是我的适配器文件:
import DS from 'ember-data';
import config from '../config/environment';
export default DS.ActiveModelAdapter.extend({
namespace: 'v1',
host: config.apiUrl,
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
urlForFindRecord: function(id, modelName, snapshot) {
Ember.debug('urlForFindRecord is being called');
if (this.urlForFind !== urlForFind) {
Ember.deprecate('BuildURLMixin#urlForFind has been deprecated and renamed to `urlForFindRecord`.');
return this.urlForFind(id, modelName, snapshot);
}
return this._buildURL(modelName, id);
},
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
findRecord: function(store, type, id, snapshot) {
Ember.debug('findRecord is being called');
var find = RestAdapter.prototype.find;
if (find !== this.find) {
Ember.deprecate('RestAdapter#find has been deprecated and renamed to `findRecord`.');
return this.find(store, type, id, snapshot);
}
return this.ajax(this.buildURL(type.modelName, id, snapshot, 'findRecord'), 'GET');
},
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
urlForQuery: function(query, modelName) {
Ember.debug('urlForQuery is being called');
if (this.urlForFindQuery !== urlForFindQuery) {
Ember.deprecate('BuildURLMixin#urlForFindQuery has been deprecated and renamed to `urlForQuery`.');
return this.urlForFindQuery(query, modelName);
}
return this._buildURL(modelName);
},
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
_buildURL: function(modelName, id) {
Ember.debug('_buildURL is being called');
var url = [];
var host = get(this, 'host');
var prefix = this.urlPrefix();
var path;
if (modelName) {
path = this.pathForType(modelName);
if (path) { url.push(path); }
}
if (id) { url.push(encodeURIComponent(id)); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url && url.charAt(0) !== '/') {
url = '/' + url;
}
return url;
},
});
有没有一种更简单的方法可以在不覆盖适配器方法的情况下完成我想要做的事情?如果没有,我需要重写哪些方法?
提前感谢您的帮助!
【问题讨论】:
标签: javascript ember.js