-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
Entity.ts
218 lines (200 loc) · 7.02 KB
/
Entity.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import SimpleRecord from './SimpleRecord';
import { isImmutable, denormalizeImmutable } from '../schemas/ImmutableUtils';
import * as schema from '../schema';
import { AbstractInstanceType, Schema } from '../types';
/** Represents data that should be deduped by specifying a primary key. */
export default abstract class Entity extends SimpleRecord {
/**
* A unique identifier for each Entity
*
* @param [parent] When normalizing, the object which included the entity
* @param [key] When normalizing, the key where this entity was found
*/
abstract pk(parent?: any, key?: string): string | undefined;
/** Returns the globally unique identifier for the static Entity */
static get key(): string {
/* istanbul ignore next */
if (
process.env.NODE_ENV !== 'production' &&
(this.name === '' || this.name === 'Entity')
)
throw new Error(
'Entity classes without a name must define `static get key()`',
);
return this.name;
}
/** Defines indexes to enable lookup by */
declare static indexes?: readonly string[];
/**
* A unique identifier for each Entity
*
* @param [value] POJO of the entity or subset used
* @param [parent] When normalizing, the object which included the entity
* @param [key] When normalizing, the key where this entity was found
*/
static pk<T extends typeof Entity>(
this: T,
value: Partial<AbstractInstanceType<T>>,
parent?: any,
key?: string,
): string | undefined {
return this.prototype.pk.call(value, parent, key) || key;
}
static normalize(
input: any,
parent: any,
key: string | undefined,
visit: (...args: any) => any,
addEntity: (...args: any) => any,
visitedEntities: Record<string, any>,
): any {
// pass over already processed entities
if (typeof input === 'string') return input;
// TODO: what's store needs to be a differing type from fromJS
const processedEntity = this.fromJS(input, parent, key);
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
const instanceSample = new (this as any)();
const keysOfRecord = new Set(Object.keys(instanceSample));
const keysOfProps = this.keysDefined(processedEntity);
const [found, missing, unexpected] = [[], [], []] as [
string[],
string[],
string[],
];
for (const keyOfProps of keysOfProps) {
if (keysOfRecord.has(keyOfProps)) {
found.push(keyOfProps);
} else {
unexpected.push(keyOfProps);
}
}
for (const keyOfRecord of keysOfRecord) {
if (!found.includes(keyOfRecord)) {
missing.push(keyOfRecord);
}
}
// if we find nothing, or we find too many unexpected members
if (
((Math.max(keysOfProps.length / 2, 1) <= unexpected.length &&
keysOfRecord.size > Math.max(unexpected.length, 2)) ||
found.length < Math.min(1, keysOfRecord.size / 2)) &&
keysOfRecord.size
) {
const error = new Error(
`Attempted to initialize ${
this.name
} with substantially different than expected keys
This is likely due to a malformed response.
Try inspecting the network response or fetch() return value.
Expected keys:
Found: ${found}
Missing: ${missing}
Unexpected keys: ${unexpected}
Value: ${JSON.stringify(this.toObjectDefined(processedEntity), null, 2)}`,
);
(error as any).status = 400;
throw error;
}
}
const id = processedEntity.pk(parent, key);
if (id === undefined || id === '') {
if (process.env.NODE_ENV !== 'production') {
const error = new Error(
`Missing usable resource key when normalizing response.
This is likely due to a malformed response.
Try inspecting the network response or fetch() return value.
Entity: ${this.name}
Value: ${input && JSON.stringify(input, null, 2)}
`,
);
(error as any).status = 400;
throw error;
} else {
// these make the keys get deleted
return undefined;
}
}
const entityType = this.key;
if (!(entityType in visitedEntities)) {
visitedEntities[entityType] = {};
}
if (!(id in visitedEntities[entityType])) {
visitedEntities[entityType][id] = [];
}
if (
visitedEntities[entityType][id].some((entity: any) => entity === input)
) {
return id;
}
visitedEntities[entityType][id].push(input);
Object.keys(this.schema).forEach(key => {
if (Object.hasOwnProperty.call(processedEntity, key)) {
const schema = this.schema[key];
processedEntity[key] = visit(
processedEntity[key],
processedEntity,
key,
schema,
addEntity,
visitedEntities,
);
}
});
addEntity(this, processedEntity, processedEntity, parent, key);
return id;
}
static denormalize<T extends typeof SimpleRecord>(
this: T,
entity: AbstractInstanceType<T>,
unvisit: schema.UnvisitFunction,
): [AbstractInstanceType<T>, boolean] {
// TODO: this entire function is redundant with SimpleRecord, however right now we're storing the Entity instance
// itself in cache. Once we offer full memoization, we will store raw objects and this can be consolidated with SimpleRecord
if (isImmutable(entity)) {
const [denormEntity, found] = denormalizeImmutable(
this.schema,
entity,
unvisit,
);
return [this.fromJS(denormEntity.toObject()), found];
}
// TODO: This creates unneeded memory pressure
const instance = new (this as any)();
let found = true;
const denormEntity = entity;
Object.keys(this.schema).forEach(key => {
const schema = this.schema[key];
const input = this.hasDefined(entity, key as any)
? entity[key]
: undefined;
const [value, foundItem] = unvisit(input, schema);
// members who default to falsy values are considered 'optional'
// if falsy value, and default is actually set then it is optional so pass through
if (!foundItem && !(key in instance && !instance[key])) {
found = false;
}
if (this.hasDefined(entity, key as any) && denormEntity[key] !== value) {
denormEntity[key] = value;
}
});
return [denormEntity as any, found];
}
}
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production') {
// for those not using TypeScript this is a good catch to ensure they are defining
// the abstract members
Entity.fromJS = function fromJS<T extends typeof SimpleRecord>(
this: T,
props: Partial<AbstractInstanceType<T>>,
): AbstractInstanceType<T> {
if ((this as any).prototype.pk === undefined)
throw new Error('cannot construct on abstract types');
return SimpleRecord.fromJS.call(this, props) as any;
};
}
export function isEntity(schema: Schema | null): schema is typeof Entity {
return schema !== null && (schema as any).pk !== undefined;
}