/
resource.ts
400 lines (357 loc) · 10.1 KB
/
resource.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import config from "../config";
const resourceTypes: Record<string, string> = {
dataLayerValidations: "data_layer_validations",
steps: "steps",
suites: "suites",
tagValidations: "tag_validations",
tests: "tests",
};
export interface ResourceOptions {
description?: string,
position?: number,
}
/**
* Base class for all DataTrue resource types
*/
export default abstract class Resource {
public static readonly resourceType: string;
public static readonly childTypes: readonly string[];
public static readonly resourceTypeRun?: string;
protected toDelete: Resource[] = [];
protected resourceID?: number;
protected contextID?: number;
protected abstract readonly contextType: string;
public options: ResourceOptions = {};
public constructor(public name: string) { }
/**
* Create a resource from a given ID
*
* @param id the ID of the resource
* @returns Promise of the resource
*/
public static fromID(id: number): Promise<Resource> { // eslint-disable-line @typescript-eslint/no-unused-vars
return Promise.reject(new Error("Function not implemented"));
}
/**
* Create a resource from an object
*
* @param obj object to create resource from
* @param copy whether to create a copy of the resource or not (removes resource IDs)
* @returns new Resource
*/
public static fromJSON(obj: Record<string, any>, copy: boolean = false): Resource { // eslint-disable-line @typescript-eslint/no-unused-vars
throw new Error("Function not implemented");
}
/**
* Convert the resource to an Object
*
* @returns object representation of the resource
*/
public abstract toJSON(): Promise<Record<string, any>>;
/**
* Convert the resource to a JSON string
*
* @returns the resource represented as a JSON string
*/
public async toString(): Promise<string> {
return JSON.stringify(await this.toJSON());
}
/**
* Gets the resourceID of a resource
*
* @returns resourceID of the resource
*/
public getResourceID(): number | undefined {
return this.resourceID;
}
/**
* Gets the contextID of a resource
*
* @returns contextID of the resource
*/
public getContextID(): number | undefined {
return this.contextID;
}
/**
* Gets the contextType of a resource
*
* @returns contextType of the resource
*/
public getContextType(): string {
return this.contextType;
}
/**
* Sets the resourceID of a resource
*
* @param id the resourceID to set
*/
public setResourceID(id: number | undefined): void {
this.resourceID = id;
(this.constructor as typeof Resource).childTypes.forEach(
(childType: string) => {
if ((this as Record<string, any>)[childType] !== undefined) {
(this as Record<string, any>)[childType].forEach(
(child: Resource) => {
child.setContextID(id);
}
);
}
}
);
}
/**
* Sets the contextID of a resource
*
* @param id the contextID to set
*/
public setContextID(id: number | undefined): void {
this.contextID = id;
}
/**
* Set options from the passed options object
*
* @param options the object to set options from
* @param override whether to override the options object
*/
public setOptions(options: ResourceOptions, override?: boolean): void {
if (override) {
this.options = options;
} else {
this.options = {
...this.options,
...options,
};
}
}
/**
* Fetch a resource from DataTrue
*
* @param id the id of the resource to fetch
* @param resourceType the type of the resource to fetch
* @returns Promise of the resource as a JSON string
*/
protected static async getResource(
id: number,
resourceType: string
): Promise<string> {
const uri = [
config.apiEndpoint,
"management_api/v1",
resourceType + "s",
id].join("/");
const response = await config.httpClient.makeRequest(uri, "get", {
headers: {
"authorization": "Token " + config.userToken,
},
});
if (response.status >= 400) {
throw new Error(`Failed to retrieve ${resourceType} ${id}`);
}
return response.body;
}
/**
* Save a resource to DataTrue
*
* @returns Promise
*/
public async save(): Promise<void> {
const after = async (): Promise<void> => {
const promises = this.toDelete.slice().reverse().map((child, i) => {
return child.delete().then(() => {
this.toDelete.splice(-1 - i, 1);
});
});
await Promise.all(promises);
};
if (this.resourceID) {
try {
await this.update();
return after();
} catch (e) {
throw new Error(
`Failed to save ${
(this.constructor as typeof Resource).resourceType
} ${this.getResourceID()}`
);
}
} else {
try {
await this.create();
return after();
} catch (e) {
throw new Error(
`Failed to save ${(this.constructor as typeof Resource).resourceType}`
);
}
}
}
/**
* Create the resource in DataTrue
*
* @returns Promise
*/
protected async create(): Promise<void> {
const resourceType: string = (
this.constructor as typeof Resource
).resourceType;
const uri = [
config.apiEndpoint,
"management_api/v1",
this.contextType + "s",
this.contextID,
resourceType + "s"].join("/");
const payload = await this.toJSON();
const response = await config.httpClient.makeRequest(uri, "post", {
body: JSON.stringify(this.beforeCreate(payload)),
headers: {
"authorization": "Token " + config.userToken,
},
});
if (response.status >= 400) {
throw new Error(response.body);
}
const responseObj = JSON.parse(response.body);
this.setResourceID(responseObj[resourceType]["id"]);
// Sets resource IDs for all children that were created
(this.constructor as typeof Resource).childTypes.forEach(
(childType: string) => {
if (responseObj[resourceType][resourceTypes[childType]] !== undefined) {
responseObj[resourceType][resourceTypes[childType]].forEach(
(childObj: Record<string, any>, index: number) => {
(this as Record<string, any>)[childType][index].setResourceID(
childObj["id"]
);
}
);
}
}
);
}
/**
* Update the resource and all children in DataTrue
*
* @returns Promise
*/
protected async update(): Promise<void> {
const uri = [
config.apiEndpoint,
"management_api/v1",
(this.constructor as typeof Resource).resourceType + "s",
this.resourceID].join("/");
const payload = await this.toJSON();
const response = await config.httpClient.makeRequest(uri, "put", {
body: JSON.stringify(this.beforeUpdate(payload)),
headers: {
"authorization": "Token " + config.userToken,
},
});
if (response.status >= 400) {
throw new Error(response.body);
}
const promises = (this.constructor as typeof Resource).childTypes.flatMap(
(childType: string) => {
return (this as Record<string, any>)[childType].map(
(child: Resource) => {
return child.save();
}
);
}
);
await Promise.all(promises);
}
/**
* Add a child to a resource
*
* @param child child to add to the Resource
* @param index index to add the child at
* @param resourceType type of the child
*/
protected insertChild(
child: Record<string, any>,
index: number = 0,
resourceType: string
): void {
(this as Record<string, any>)[resourceType].splice(index, 0, child);
if (
(this.constructor as typeof Resource).childTypes.includes(resourceType)
) {
(this as Record<string, any>)[resourceType].forEach(
(child: Resource, index: number) => {
child.setOptions({ position: index + 1 });
}
);
}
}
/**
* Delete a child from a resource
*
* @param index index to delete the child from
* @param childType type of the child
*/
protected deleteChild(index: number, childType: string): void {
this.toDelete.push((this as Record<string, any>)[childType][index]);
(this as Record<string, any>)[childType].splice(index, 1);
}
/**
* Format the object to the required specifications to create
*
* @param obj object to create
* @returns object in correct format for DataTrue
*/
private beforeCreate(obj: Record<string, any>): Record<string, any> {
return {
[(this.constructor as typeof Resource).resourceType]: obj,
};
}
/**
* Removes children from obj so that the Resource can be updated
*
* @param obj object to remove children from
* @returns obj without children
*/
private beforeUpdate(obj: Record<string, any>): Record<string, any> {
for (const childType of (this.constructor as typeof Resource).childTypes) {
if (
obj[(this.constructor as typeof Resource).resourceType] !== undefined
) {
delete obj[(this.constructor as typeof Resource).resourceType][resourceTypes[childType]];
} else {
delete obj[resourceTypes[childType]];
}
}
if ((this.constructor as typeof Resource).resourceType === "test") {
return {
test: obj,
};
} else {
return obj;
}
}
/**
* Delete the resource in DataTrue
*
* @returns Promise
*/
public async delete(): Promise<void> {
if (this.resourceID === undefined) {
return;
}
const uri = [
config.apiEndpoint,
"management_api/v1",
(this.constructor as typeof Resource).resourceType + "s",
this.resourceID].join("/");
const response = await config.httpClient.makeRequest(uri, "delete", {
headers: {
"authorization": "Token " + config.userToken,
},
});
if (response.status >= 400) {
throw new Error(
`Failed to delete ${
(this.constructor as typeof Resource).resourceType
} ${this.getResourceID()}`
);
}
}
}