Skip to content

Commit 489e1ad

Browse files
committed
feat: Allow normalizing entities that are just ids (#1002)
1 parent 8d4e12a commit 489e1ad

File tree

2 files changed

+26
-18
lines changed

2 files changed

+26
-18
lines changed

packages/normalizr/src/__tests__/index.test.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// eslint-env jest
22
import { fromJS } from 'immutable';
3-
import { after } from 'lodash';
43

54
import { denormalizeSimple as denormalize } from '../denormalize';
65
import { normalize, schema } from '../';
@@ -37,10 +36,23 @@ describe('normalize', () => {
3736
expect(normalize(input).result).toBe(input);
3837
});
3938

39+
test('passthrough with id in place of entity', () => {
40+
const input = { taco: 5 };
41+
expect(normalize(input, { taco: Tacos }).result).toStrictEqual(input);
42+
});
43+
4044
test('cannot normalize with null input', () => {
4145
expect(() => normalize(null, Tacos)).toThrow(/null/);
4246
});
4347

48+
test('passthrough primitive schema', () => {
49+
expect(normalize({ happy: { bob: 5 } }, { happy: 5 }).result).toStrictEqual(
50+
{
51+
happy: { bob: 5 },
52+
},
53+
);
54+
});
55+
4456
test('can normalize string', () => {
4557
const mySchema = '';
4658
expect(normalize('bob', mySchema)).toMatchInlineSnapshot(`

packages/normalizr/src/normalize.ts

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,13 @@ const visit = (
1616
addEntity: any,
1717
visitedEntities: any,
1818
) => {
19-
if (!value || !schema || !['function', 'object'].includes(typeof schema)) {
19+
if (!value || !schema) {
2020
return value;
2121
}
2222

23-
if (!schema.normalize || typeof schema.normalize !== 'function') {
24-
// serializable
25-
if (typeof schema === 'function') {
26-
return new schema(value);
27-
}
28-
const method = Array.isArray(schema) ? arrayNormalize : objectNormalize;
29-
return method(
30-
schema,
23+
if (schema.normalize && typeof schema.normalize === 'function') {
24+
if (typeof value !== 'object') return value;
25+
return schema.normalize(
3126
value,
3227
parent,
3328
key,
@@ -37,14 +32,15 @@ const visit = (
3732
);
3833
}
3934

40-
return schema.normalize(
41-
value,
42-
parent,
43-
key,
44-
visit,
45-
addEntity,
46-
visitedEntities,
47-
);
35+
// serializable
36+
if (typeof schema === 'function') {
37+
return new schema(value);
38+
}
39+
40+
if (typeof value !== 'object' || typeof schema !== 'object') return value;
41+
42+
const method = Array.isArray(schema) ? arrayNormalize : objectNormalize;
43+
return method(schema, value, parent, key, visit, addEntity, visitedEntities);
4844
};
4945

5046
const addEntities =

0 commit comments

Comments
 (0)