在Ember中规范化错误有效负载

时间:2013-12-18 20:30:33

标签: ember.js ember-data

假设我有Person模型

App.Person = DS.Model.extend
  firstName: DS.attr 'string'
  lastName: DS.attr 'string'
  email: DS.attr 'string'

我正在使用ember-data,调用使用下划线属性名称的REST API(即firstNamefirst_name),因此我正在自定义{{1}执行“全面”规范化(参见docs)。

ApplicationSerializer

这对于序列化和规范化与服务器之间的数据非常有用。但是,服务器的错误呢?

假设我有一个动作尝试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_nameajaxError作为他的回答中提到的kingpin2k,而不是覆盖ActiveModelSerializer钩子。这将标准化并将数据和错误从下划线属性序列化为camelCased属性。

1 个答案:

答案 0 :(得分:0)

覆盖适配器上的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;
    }
  }

});