在 ember 序列化程序上定义自定义根 json 节点

Define custom root json node on ember serializer

我正在尝试使用 ember 从我的 REST API 获取品牌商品;但我的 API 响应与预期的 ember 数据不匹配。例如:

我的模特:

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    isActive: DS.attr('boolean')
});

我的 API url: http://localhost:3000/api/brands 它的回应是:

{"success":true,
     "data":[
        {"id":1,"name":"Mine","isActive":true,"createdAt":"2017-04-23T20:36:49.000Z","updatedAt":"2017-04-23T20:44:32.000Z"},
        {"id":2,"name":"forever","isActive":true,"createdAt":"2017-04-23T20:41:14.000Z","updatedAt":"2017-04-23T20:43:57.000Z"}
    ]
}

但是,Ember 期待这样的结果:

"brands": [{

    "id": 1,
    "name": "foo",
    "isActive": "foo"

}]

我正在尝试更改名为 brand.js 的序列化程序中的根 json 节点,但我无法使其工作。 :(

这里是我的 serializer/brand.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({

});

和我的 adapters/application.js

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
import config from '../config/environment';


export default DS.RESTAdapter.extend(DataAdapterMixin, {  
    host: `${config.host}`,
    namespace: `${config.namespace}`,
    authorizer: 'authorizer:custom'
});

在浏览器控制台上显示此消息:

WARNING: Encountered "success" in payload, but no model was found for model name "success" (resolved model name using vanely-web@serializer:brand:.modelNameFromPayloadKey("success"))
WARNING: Encountered "data" in payload, but no model was found for model name "datum" (resolved model name using vanely-web@serializer:brand:.modelNameFromPayloadKey("data"))

我如何告诉 ember 正确的数据在哪里?感谢您的帮助。

对不起,如果我的英语不好。

正如您已经做的那样,您可以覆盖每个模型的 RESTSerializer。

你想要实现的是响应规范化。您可以通过在序列化程序 (see the docs) 中覆盖 normalizeResponse 来规范您的响应:

import Ember from 'ember';
import DS from 'ember-data';

const {
  RESTSerializer
} = DS;

const {
  get
} = Ember;

export default RESTSerializer.extend({
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    // Only do normalization for reading:
    if(requestType !== 'createRecord' && requestType !== 'updateRecord' && requestType !== 'deleteRecord') {
      // Do your normalization here. For example (not tested):
      payload = {
        brands: get(payload, 'data')
      };
    }

    return this._super(store, primaryModelClass, payload, id, requestType);
  }
});

除了覆盖 normalizeResponse,您还可以覆盖 other normalization methods