-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
normalize.ts
169 lines (157 loc) · 4.31 KB
/
normalize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import * as ArrayUtils from './schemas/Array';
import * as ObjectUtils from './schemas/Object';
import {
NormalizeNullable,
NormalizedSchema,
Schema,
NormalizedIndex,
} from './types';
const visit = (
value: any,
parent: any,
key: any,
schema: any,
addEntity: any,
visitedEntities: any,
) => {
if (!value || !schema || !['function', 'object'].includes(typeof schema)) {
return value;
}
if (!schema.normalize || typeof schema.normalize !== 'function') {
// serializable
if (typeof schema === 'function') {
return new schema(value);
}
const method = Array.isArray(schema)
? ArrayUtils.normalize
: ObjectUtils.normalize;
return method(
schema,
value,
parent,
key,
visit,
addEntity,
visitedEntities,
);
}
return schema.normalize(
value,
parent,
key,
visit,
addEntity,
visitedEntities,
);
};
const addEntities = (entities: Record<string, any>, indexes: any) => (
schema: any,
processedEntity: any,
value: any,
parent: any,
key: string,
) => {
const schemaKey = schema.key;
const id = schema.pk(value, parent, key);
if (!(schemaKey in entities)) {
entities[schemaKey] = {};
}
const existingEntity = entities[schemaKey][id];
if (existingEntity) {
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity);
} else {
entities[schemaKey][id] = processedEntity;
}
// update index
if (Array.isArray(schema.indexes)) {
const entity = entities[schemaKey][id];
if (!(schemaKey in indexes)) {
indexes[schemaKey] = {};
}
for (const index of schema.indexes) {
if (!(index in indexes[schemaKey])) {
indexes[schemaKey][index] = {};
}
const indexMap = indexes[schemaKey][index];
if (existingEntity) {
delete indexMap[existingEntity[index]];
}
if (index in entity) {
indexMap[entity[index]] = id;
} /* istanbul ignore next */ else if (
// eslint-disable-next-line no-undef
process.env.NODE_ENV !== 'production'
) {
console.warn(`Index not found in entity. Indexes must be top-level members of your entity.
Index: ${index}
Entity: ${JSON.stringify(entity, undefined, 2)}`);
}
}
}
};
function expectedSchemaType(schema: Schema) {
return ['object', 'function'].includes(typeof schema)
? 'object'
: typeof schema;
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const normalize = <
S extends Schema = Schema,
E extends Record<string, Record<string, any>> = Record<
string,
Record<string, any>
>,
R = NormalizeNullable<S>
>(
input: any,
schema: S,
): NormalizedSchema<E, R> => {
const schemaType = expectedSchemaType(schema);
if (input === null || typeof input !== schemaType) {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
const parseWorks = (input: string) => {
try {
return typeof JSON.parse(input) !== 'string';
} catch (e) {
return false;
}
};
if (typeof input === 'string' && parseWorks(input)) {
throw new Error(`Normalizing a string, but this does match schema.
Parsing this input string as JSON worked. This likely indicates fetch function did not parse
the JSON. By default, this only happens if "content-type" header includes "json".
See https://resthooks.io/docs/guides/custom-networking for more information
Schema: ${JSON.stringify(schema, undefined, 2)}
Input: "${input}"`);
} else {
throw new Error(
`Unexpected input given to normalize. Expected type to be "${schemaType}", found "${
input === null ? 'null' : typeof input
}".
Schema: ${JSON.stringify(schema, undefined, 2)}
Input: "${input}"`,
);
}
} else {
throw new Error(
`Unexpected input given to normalize. Expected type to be "${schemaType}", found "${
input === null ? 'null' : typeof input
}".`,
);
}
}
const entities: E = {} as any;
const indexes: NormalizedIndex = {};
const addEntity = addEntities(entities, indexes);
const visitedEntities = {};
const result = visit(
input,
input,
undefined,
schema,
addEntity,
visitedEntities,
);
return { entities, indexes, result };
};