/
application.ts
210 lines (177 loc) · 5.9 KB
/
application.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
import flatten = require("flatten");
import OperationProcessor from "./processors/operation-processor";
import Resource from "./resource";
import {
Operation,
OperationResponse,
Links
} from "./types";
import pick from "./utils/pick";
import unpick from "./utils/unpick";
export default class Application {
namespace: string;
types: typeof Resource[];
processors: typeof OperationProcessor[];
defaultProcessor: typeof OperationProcessor;
user: Resource;
services: { [key: string]: any };
constructor(settings: {
namespace?: string;
types?: typeof Resource[];
processors?: typeof OperationProcessor[];
defaultProcessor?: typeof OperationProcessor;
services?: {};
}) {
this.namespace = settings.namespace || "";
this.types = settings.types || [];
this.processors = settings.processors || [];
this.services = settings.services || {};
this.defaultProcessor = settings.defaultProcessor || OperationProcessor;
}
async executeOperations(ops: Operation[]): Promise<OperationResponse[]> {
return await this.createTransaction(
ops
.map(async op => {
const processor = await this.processorFor(op.ref.type);
if (processor) {
return this.executeOperation(op, processor);
}
})
.filter(Boolean)
);
}
async executeOperation(
op: Operation,
processor: OperationProcessor<Resource>
): Promise<OperationResponse> {
const result = await processor.execute(op);
return this.buildOperationResponse(result);
}
async createTransaction(ops: Promise<OperationResponse>[]) {
return await Promise.all(ops);
}
async processorFor(
resourceType: string
): Promise<OperationProcessor<Resource> | undefined> {
const resourceClass = await this.resourceFor(resourceType);
const processors = await Promise.all(
this.processors.map(async processor =>
(await processor.shouldHandle(resourceType)) ? processor : false
)
);
const processor = processors.find(p => p !== false);
if (processor) {
return new processor(this);
}
class ResourceProcessor extends this.defaultProcessor<Resource> {
static resourceClass = resourceClass;
}
return new ResourceProcessor(this);
}
async resourceFor(resourceType: string): Promise<typeof Resource> {
return this.types.find(({ type }) => type && type === resourceType);
}
async buildOperationResponse(
data: Resource | Resource[] | void
): Promise<OperationResponse> {
const included = flatten(await this.extractIncludedResources(data)).filter(
Boolean
);
const uniqueIncluded =
[...new Set(included.map((item: Resource) => `${item.type}_${item.id}`))]
.map(type_id =>
included.find((item: Resource) => (`${item.type}_${item.id}` === type_id))
);
return included.length ?
{ included: uniqueIncluded, data: this.serializeResources(data) } :
{ data: this.serializeResources(data) };
}
serializeResources(data: Resource | Resource[] | void) {
if (!data) {
return null;
}
if (Array.isArray(data)) {
return data.map(record => this.serializeResources(record));
}
Object.keys(data.relationships).forEach(relationshipName => {
const relationships = this.serializeRelationship((data.relationships[
relationshipName
] as unknown) as Resource | Resource[]);
if (relationships.length) {
data.relationships[relationshipName] = {
data: relationships,
links: {} as Links
};
} else {
data.relationships[relationshipName] = relationships;
}
});
return data;
}
serializeRelationship(relationships: Resource | Resource[]) {
if (Array.isArray(relationships)) {
return relationships.map(relationship =>
this.serializeRelationship(relationship)
);
}
return pick(relationships, ["id", "type"]);
}
// TODO: remove type any for data.relationships[relationshipName]
async extractIncludedResources(data: Resource | Resource[] | void) {
if (!data) {
return null;
}
if (Array.isArray(data)) {
return Promise.all(
data.map(record => this.extractIncludedResources(record))
);
}
const resourceClass = await this.resourceFor(data.type);
const schemaRelationships = resourceClass.schema.relationships;
Object.keys(data.relationships).forEach(relationshipName => {
if (Array.isArray(data.relationships[relationshipName])) {
data.relationships[relationshipName] =
(data.relationships[relationshipName] as any).map(rel => {
rel["type"] = schemaRelationships[relationshipName].type().type;
return rel;
});
} else {
data.relationships[relationshipName]["type"] = schemaRelationships[
relationshipName
].type().type;
}
});
return Promise.all(
Object.values(data.relationships).map(async relatedResource => {
if (Array.isArray(relatedResource)) {
return Promise.all(
relatedResource.map(async relResource => {
const relatedResourceClass = await this.resourceFor(
relResource["type"]
);
const resource = relResource[0] || relResource;
if (!resource["id"]) {
return;
}
return new relatedResourceClass({
id: resource["id"],
attributes: unpick(resource, ["id", "type"])
});
})
);
}
const relatedResourceClass = await this.resourceFor(
relatedResource["type"]
);
const resource = relatedResource[0] || relatedResource;
if (!resource["id"]) {
return;
}
return new relatedResourceClass({
id: resource["id"],
attributes: unpick(resource, ["id", "type"])
});
})
);
}
}