0

假设一个用户收藏了许多猫,当被问及用户的收藏时,api 端点给出了一个猫列表:

const catsList = [{id:1,name:"catA"},{id:2,name:"catB"},{id:3,name:"catC"}];

// ex: GET http://app.com/api/favorites =>  results in following json
{favorites:[{id:2,name:"catB"},{id:3,name:"catC"}]} 
// the result is the list of cats 

//and normalizr schema 
const cats = new Schema('cats');
const favorites = new Schema('favorites');

现在我的问题是,我将如何规范化这些实体,以便得到以下结果,

  entities.favorites=[2,3]; //2 and 3 are cats
  entities.cats=[{id:1,name:"a"},{id:2,name:"b"},{id:3,name:"c"}];

我将如何使用 normalizr 完成此操作?

4

1 回答 1

0

就像是

const cats = new Schema('cats');

const response = {
  favorites: [{
    id: 2,
    name: "catB"
  }, {
    id: 3,
    name: "catC"
  }]
}

const normalized = normalize(response, {
  favorites: arrayOf(cats)
})

价值会normalized

{
  result: {
    favorites: [2, 3]
  },
  entities: {
    cats: {
      2: {
        id: 2,
        name: "catB"
      }, {
        id: 3,
        name: "catC"
      }
    }
  }
}

实际上,normalized.entities对象而不是数组非常重要——否则通过 ID 查询会很慢。

此时,您可以随意转换此表示。

于 2016-03-07T03:13:52.593 回答