Belladonna
Belladonna

Reputation: 3862

Normalize api response with normalizr

So the endpoint responds with something like this when you request an asset. Bios is just an example.

{
  _embedded: {
    bios: [
      {
        name: 'Blorp Gorp',
        id: 256,
        _links: {},
        arrayCollection: [...],
        objectCollection: [...],
        ...
      },
      ...
    ],
  _links: {},
}

And I'd like to flatten it to something like, and I'm not even sure this makes sense:

{
  results: [256, 257],
  entities: {
    bios: {
      256: {...},
      257: {...}
    },
    arrayCollection: {
      256: [...],
      257: [...]
    },
    objectCollection: {
      256: {...},
      257: {...}
    }
  }
}

But I can't get the Schemas to recognize any nesting before they hit their entity. if I pass normalize(camelizedJson.embedded.bios, bioSchema), it works, but if I pass it normalize(camelizedJson.embedded, bioSchema) I can't get it realize I want to parse the bios.

I suppose I could pass another variable into the middleware that gives it the embedded key to parse successfully.

Upvotes: 0

Views: 725

Answers (2)

Dan Abramov
Dan Abramov

Reputation: 268265

But I can't get the Schemas to recognize any nesting before they hit their entity. if I pass normalize(camelizedJson.embedded.bios, bioSchema), it works, but if I pass it normalize(camelizedJson.embedded, bioSchema) I can't get it realize I want to parse the bios.

You probably want normalize(camelizedJson.embedded, { bios: bioSchema }) instead. Schemas can be nested inside plain JavaScript objects, for example:

normalize(camelizedJson.embedded, {
  bios: bioSchema,
  lols: lolSchema,
  wow: arrayOf({
    wat: {
      ugh: ughSchema
    }
  })
})

Upvotes: 2

markerikson
markerikson

Reputation: 67539

I believe you need to create a schema that defines (fake names for illustration here) "MyArrayThing" and "MyObjectThing", then in the "Bio" schema definition, define the "arrayCollection" and "objectCollection" sub-fields using Normalizr's arrayOf(SomeSchemaObject) function. Then, once you've defined what a single Bio object looks like, your parsing command also needs to look roughly like normalize(camelizedJson.embedded.bios, arrayOf(Bio)).

Upvotes: 0

Related Questions