从processStrategy访问父属性

时间:2017-11-28 15:47:53

标签: normalizr

我有以下架构:

const dataPointSchema = new schema.Entity(
  DATA_POINT_ENTITY_TYPE,
  undefined,
  {
    processStrategy: (value, parent) => {
      console.log({parent});
      return value;
    }
  }
);
const dataPointsSchema = new schema.Array(dataPointSchema);
const dataRowSchema = new schema.Entity(
  DATA_ROW_ENTITY_TYPE,
  {_embedded: {'data-points': dataPointsSchema}}
);

const dataRowsSchema = new schema.Array(dataRowSchema);

return normalize(dataRows, dataRowsSchema);

当我parent拥有normalize的所有属性时,我希望data-row打印出来,但它只显示我告诉它的data-points关于dataRowSchema。这是一个错误还是预期的行为?

看起来正在发生的事情是_embeddeddataPointSchema流程策略中的父项。一个工作的例子如下:

import {normalize, schema} from 'normalizr';

const someDataRows = [
{
  _embedded: {'data-points': [{id: 'Uv2k4uW_-6xzh8ImYNwh-0'}]},
  id: 'Uv2k4uW_-6xzh8ImYNwh',
  blah: 'hello'
},
{
  _embedded: {'data-points': [{id: '-B0jeFmCROeL5ICJpx-b'}]},
  id: 'D01A08',
  blah: 'hello1'
}
];

function normalizeRows(dataRows) {
  const dataPointSchema = new schema.Entity(
    'data-point',
    undefined,
    {
      processStrategy: (value, parent) => {
        console.log({parent});
        return value;
      }
    }
  );
  const dataPointsSchema = new schema.Array(dataPointSchema);
  const dataRowSchema = new schema.Entity(
    'data-row',
    {_embedded: {'data-points': dataPointsSchema}}
  );

  const dataRowsSchema = new schema.Array(dataRowSchema);

  return normalize(dataRows, dataRowsSchema);
}

normalizeRows(someDataRows);

1 个答案:

答案 0 :(得分:2)

这是正确的行为。 parent是父对象,恰好是_embedded的值。从技术上讲,普通对象是一种非唯一的模式。这可以不用速记重写,因此更有意义:

const dataRowSchema = new schema.Entity(
    'data-row',
    {_embedded: new schema.Object({'data-points': dataPointsSchema}})
);