gpbl/denormalizr

Calling a function on each object after denormalization

Open

#19 opened on Sep 13, 2016

View on GitHub
 (1 comment) (0 reactions) (0 assignees)JavaScript (24 forks)github user discovery
enhancementhelp wanted

Repository metrics

Stars
 (229 stars)
PR merge metrics
 (PR metrics pending)

Description

I have the need to call a function objects, including nested objects, after they've been denormalized. Since it includes nested entities, if I waited until the entire object was denormalized I'd have to re-traverse all of the nested schemas manually, which I'd like to avoid.

To give more context of my specific use-case, I'm storing raw data in a normalized store and I need to instantiate classes from these object on the way out.

I think it would be a fairly simple/straightforward change to the denormalizeObject function:

function denormalizeObject(obj, entities, schema, bag) {
  let denormalized = obj

  Object.keys(schema)
    .filter(attribute => attribute.substring(0, 1) !== '_')
    .filter(attribute => typeof getIn(obj, [attribute]) !== 'undefined')
    .forEach(attribute => {

      const item = getIn(obj, [attribute]);
      const itemSchema = getIn(schema, [attribute]);

      denormalized = setIn(denormalized, [attribute], denormalize(item, entities, itemSchema, bag));
    });

  // New line
  const { transform = _.identity } = bag

  return transform(denormalized);
}

The one issue that I see is that the bag field is the last argument to denormalize. I think just passing the transform key directly there should be fine but there's a non-zero chance it would collide with a key during denormalization if that happened to be a string key. Super edge-case IMHO, but we could either make that key more specific (e.g. transformObject) or prefix it with a _ (e.g. _transform or _transformObject) if you think that's an issue.

Let me know if this makes sense and I can put together a PR with specs.

Contributor guide