Created
June 2, 2017 02:52
-
-
Save wrumsby/2fab2d604d00f5569f1ed3a5b9bf01a3 to your computer and use it in GitHub Desktop.
Normalizing and denormalizing with normalizr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { normalize, denormalize, schema } from 'normalizr'; | |
import { assert } from 'chai'; | |
const data = [ | |
{ | |
id_str: '123', | |
url: 'https://twitter.com', | |
user: { | |
id: 456, | |
name: 'Jimmy', | |
misc: [ | |
{ | |
id: 1, | |
text: 'meh' | |
}, | |
{ | |
id: 2, | |
text: 'bah' | |
} | |
] | |
} | |
}, | |
{ | |
id_str: '124', | |
url: 'https://twitter.com', | |
user: { | |
id: 457, | |
name: 'Marlene', | |
misc: [ | |
{ | |
id: 3, | |
text: 'boo' | |
} | |
] | |
} | |
} | |
]; | |
const misc = new schema.Entity('misc'); | |
const user = new schema.Entity('users', { misc: new schema.Array(misc) }); | |
const tweet = new schema.Entity('tweets', { user }, { | |
idAttribute: 'id_str' | |
}); | |
const mySchema = new schema.Array(tweet); | |
// tslint:disable:no-console | |
// tslint:disable:no-magic-numbers | |
describe('normalizr', () => { | |
describe('normalize', () => { | |
it('should normalize data to a "normalized" shape', () => { | |
const normalizedData = normalize(data, mySchema); | |
console.log(JSON.stringify(normalizedData)); | |
assert.property(normalizedData, 'entities'); | |
assert.property(normalizedData.entities, 'misc'); | |
assert.property(normalizedData.entities, 'users'); | |
assert.property(normalizedData.entities, 'tweets'); | |
assert.deepEqual(normalizedData.entities.tweets[123], { | |
id_str: '123', | |
url: 'https://twitter.com', | |
user: 456 | |
}); | |
}); | |
}); | |
describe('denormalize', () => { | |
it('should denormalize normalized data back to its original shape', () => { | |
const normalizedData = normalize(data, mySchema); | |
const denormalizedData = denormalize(normalizedData.result, mySchema, normalizedData.entities); | |
console.log(JSON.stringify(denormalizedData)); | |
assert.deepEqual(denormalizedData, data); | |
}); | |
}); | |
}); | |
// tslint:enable:no-console | |
// tslint:enable:no-magic-numbers | |
// tslint:enable:object-literal-key-quotes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
normalizedData
is:denormalizedData
is: