假设我有一个Person
模特
App.Person = DS.Model.extend
firstName: DS.attr 'string'
lastName: DS.attr 'string'
email: DS.attr 'string'
我正在使用ember-data
,调用使用带下划线的属性名称(即firstName
is first_name
)的REST API ,因此我正在自定义,ApplicationSerializer
以执行“全面”标准化(请参阅docs)。
App.ApplicationSerializer = DS.RESTSerializer.extend
keyForAttribute: (attr) ->
Ember.String.underscore(attr)
这对于与服务器之间的数据进行序列化和标准化都非常有用。但是,来自服务器的错误呢?
假设我有一个尝试尝试PUT
更新Person
记录的操作。所以我有按钮
# Somewhere in the person/edit template
<button {{action "save"}}>Save</button>
和控制器
App.PersonEditController = Ember.ObjectController.extend
actions:
save: ->
@get('model').save().then(@onDidCreate.bind(@)).fail(@onBecameError.bind(@))
onBecameError: (res) ->
@get('model').set 'errors', res.responseJSON.errors
但这在带下划线的属性名称(即{first_name: ["can't be blank"]}
)上设置了错误。为了显示错误,我必须将我的视图绑定到下划线的属性名称。然后,我的视图将同时绑定到firstName
和first_name
属性。
如何使用相同的序列化器对错误有效载荷进行标准化以保持一致性?
编辑
ajaxError
我没有覆盖问题,而是只使用了他的回答中提到的ActiveModelSerializer
andActiveModelAdapter
和kingpin2k。这将规范化和序列化数据和错误,从强调属性到camelCased属性。
覆盖适配器上的ajaxError钩子,这是活动模型适配器执行此操作的方式。
App.ApplicationAdapter = DS.RESTAdapter.extend({
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
@method ajaxError
@param jqXHR
@returns error
*/
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"],
errors = {};
forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
return new DS.InvalidError(errors);
} else {
return error;
}
}
});
您的可能相似,但忽略422
App.ApplicationAdapter = DS.RESTAdapter.extend({
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
@method ajaxError
@param jqXHR
@returns error
*/
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"],
errors = {};
forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
return new DS.InvalidError(errors);
} else {
return error;
}
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句