Skip to content
This repository has been archived by the owner on Nov 17, 2017. It is now read-only.

Calling a function on each object after denormalization #19

Open
jeffcarbs opened this issue Sep 13, 2016 · 1 comment
Open

Calling a function on each object after denormalization #19

jeffcarbs opened this issue Sep 13, 2016 · 1 comment

Comments

@jeffcarbs
Copy link
Contributor

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.

@gpbl
Copy link
Owner

gpbl commented Sep 25, 2016

Hi @jcarbo,
yes I wouldn't alter the schema definition just for denormalization. What about passing a transform option to denormalize?

const transforms = { articles: _.identity };
const denormalized = denormalize(article, normalized.entities, articleSchema, { transforms });

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants