This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
datalayer-libs.ts
519 lines (397 loc) · 14.2 KB
/
datalayer-libs.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/**
* Created by frank.zickert on 02.05.19.
*/
import AWS from 'aws-sdk';
import gql from 'graphql-tag';
import Cookies from 'universal-cookie';
import { mutation, params, types, query } from 'typed-graphqlify'
import {IC_USER_ID} from "../authentication/auth-middleware";
/**
* transforms a function into a Promise
*/
const promisify = foo => new Promise((resolve, reject) => {
foo((error, result) => {
if(error) {
reject(error)
} else {
resolve(result)
}
})
});
const applyOfflineConfig = (offline: boolean) => {
return offline ? {
region: 'localhost',
endpoint: 'http://localhost:8000'
} : {}
};
export const setEntry = (tableName, pkEntity, pkId, skEntity, skId, jsonData, isOffline) => {
//console.log("setEntry: ", pkEntity, "|", pkId, "|", skEntity, "|", skId );
return promisify(callback =>
new AWS.DynamoDB.DocumentClient(applyOfflineConfig(isOffline)).update({
TableName: tableName,
/**
* ALL KEYS MUST BE SPECIFIED HERE!
*/
Key: {
pk: `${pkEntity}|${pkId}`,
sk: `${skEntity}|${skId}`
},
UpdateExpression: `SET jsonData = :jsonData`,
ExpressionAttributeValues: {
':jsonData': `${JSON.stringify(jsonData)}`,
}
}, callback))
.then(() => {
//console.log("data stored!")
var result = {};
result[pkEntity] = pkId;
result[skEntity] = skId;
result["data"] = `${JSON.stringify(jsonData).replace(/"/g, "\\\"")}`;
return result;
}).catch(error => { console.log(error) });
};
/**
* Get all entries to a entity|value pair in the key-field whose range have the specified rangeEntity
*
* @param key specify which field is the key: pk or sk
* @param entity specifies the entity of the key-field
* @param value specify the id of the key-field
* @param rangeEntity specify the entity of the range
* @returns {Promise<string>|any}
*/
export const ddbListEntries = (tableName, key, entity, value, rangeEntity, isOffline) => {
//console.log("ddbListEntries: ", tableName, key, entity, value, rangeEntity, isOffline);
const q = {
// use the table_name as specified in the serverless.yml
TableName: tableName,
IndexName: key === "sk" ? "reverse" : undefined,
/**
* ALL KEYS MUST HAVE KEY-CONDITION-EXPRESSIONS!
*/
KeyConditionExpression: `${
key
} = :value and begins_with(${
key === "pk" ? "sk" : "pk"
}, :entity)`,
ExpressionAttributeValues: {
":value": `${entity}|${value}`,
":entity": rangeEntity ? rangeEntity : "undefined"
}
};
//console.log("query: ", q);
return promisify(callback =>
new AWS.DynamoDB.DocumentClient(applyOfflineConfig(isOffline)).query(q, callback))
.then(result => {
//console.log("ddb-result: ", result);
return result["Items"];
/*
if (result.Items) {
return result.Items.map(item => JSON.stringify(item));
}
return [];*/
//return result.Items.map(item => JSON.stringify(item));
}).catch(error => { console.log(error) });
};
export const ddbGetEntry = (tableName, pkEntity, pkValue, skEntity, skValue, isOffline) => {
//console.log("ddbGetEntry: ", `${pkEntity}|${pkValue}`, ` -- ${skEntity}|${skValue}`, " -- ", tableName);
const q = {
TableName: tableName,
Key: {
pk: `${pkEntity}|${pkValue}`,
sk: `${skEntity}|${skValue}`
}
};
//console.log("ddbGetEntry-query: ", q);
return promisify(callback =>
new AWS.DynamoDB.DocumentClient(applyOfflineConfig(isOffline)).get(q, callback))
.then(result => {
//console.log("ddbGetEntry result: ", result);
return result["Item"] ? result["Item"] : result;
}).catch(error => { console.log(error) });
};
export const ddbScan = (tableName, key, entity, start_value, end_value, rangeEntity, isOffline) => {
//console.log("scan: ", tableName, key, entity, start_value, end_value, rangeEntity, isOffline);
const q = {
// use the table_name as specified in the serverless.yml
TableName: tableName,
FilterExpression: `${
key
} between :sv and :ev and begins_with(${
key === "pk" ? "sk" : "pk"
}, :entity)`,
ExpressionAttributeValues: {
":sv": `${entity}|${start_value}`,
":ev": `${entity}|${end_value}`,
":entity": rangeEntity ? rangeEntity : "undefined"
}
};
const allQ = {
// use the table_name as specified in the serverless.yml
TableName: tableName,
FilterExpression: `begins_with(${key}, :entity) and begins_with(${
key === "pk" ? "sk" : "pk"}, :rangeentity)`,
ExpressionAttributeValues: {
":entity": entity,
":rangeentity": rangeEntity ? rangeEntity : "undefined"
}
};
//console.log("query: ", q);
return promisify(callback =>
new AWS.DynamoDB.DocumentClient(applyOfflineConfig(isOffline)).scan(start_value && end_value ? q : allQ, callback))
.then(result => {
//console.log("ddb-result: ", result);
return result["Items"];
/**
* TODO
return await client.select(Object.assign({
query: query,
context: context
}, params)).then(result => {
//console.log("select result: ", result)
return result.data.Items.concat(typeof result.data.LastEvaluatedKey != "undefined" ?
scan(
client, {
query: query,
context: context,
params: {
ExclusiveStartKey: result.data.LastEvaluatedKey
}
}
): []);
// continue scanning if we have more movies, because
// scan can retrieve a maximum of 1MB of data
if (typeof data.LastEvaluatedKey != "undefined") {
console.log("Scanning for more...");
params.ExclusiveStartKey = data.LastEvaluatedKey;
docClient.scan(params, onScan);
}
return [];*/
//return result.Items.map(item => JSON.stringify(item));
}).catch(error => { console.log(error) });
};
export const deleteEntry = (tableName, pkEntity, pkValue, skEntity, skValue, isOffline) => {
//console.log("delete entry: ", pkEntity, pkValue, skEntity, skValue)
//console.log("pk: ", `${pkEntity}|${pkValue}`);
//console.log("sk: ", `${skEntity}|${skValue}`);
return promisify(callback =>
new AWS.DynamoDB.DocumentClient(applyOfflineConfig(isOffline)).delete({
// use the table_name as specified in the serverless.yml
TableName: tableName,
Key: {
pk: `${pkEntity}|${pkValue}`,
sk: `${skEntity}|${skValue}`
}
}, callback))
.then(result => {
//console.log("result: ", result);
return result["Item"] ? result["Item"] : result;
}).catch(error => { console.log(error) });
};
/**
* this function provides a executable graphql-query
* TODO the fields must be taken from the data-layer, not requiring the user to provide them
*/
export const setEntryMutation = ( entryId, data, fields, context={}) => {
//console.log("setEntryMutation: ", entryId, data, fields);
const mutationObj = {};
mutationObj[`set_${entryId}`] = params(
Object.keys(data).reduce((result, key) => {
result[key] = `"${data[key]}"`;
return result;
},{}),
Object.keys(fields).reduce((result, key) => {
result[key] = types.string;
return result;
},{})
);
return {
mutation: gql`${mutation(mutationObj)}`,
context: context
}
};
export const deleteEntryMutation = ( entryId, data, fields, context={}) => {
//console.log("deleteEntryMutation: ", entryId, data);
const mutationObj = {};
mutationObj[`delete_${entryId}`] = params(
Object.keys(data).reduce((result, key) => {
result[key] = `"${data[key]}"`;
return result;
},{}),
Object.keys(fields).reduce((result, key) => {
result[key] = types.string;
return result;
},{})
);
return {
mutation: gql`${mutation(mutationObj)}`,
context: context
}
};
/**
* this function provides a executable graphql-query
*/
export const getEntryListQuery = ( entryId, data, fields, context={}) => {
//console.log("getEntryListQuery: ", entryId, data, fields, context);
if (data == undefined) {
console.error("getEntryListQuery requires a data argument");
return undefined;
}
if (Object.keys(data).length !== 1) {
console.error("getEntryListQuery requires exact 1 field provided in the data argument");
return undefined;
}
const queryKey = Object.keys(data)[0];
const queryObj = {};
queryObj[`list_${entryId}_${queryKey}`] = params(
Object.keys(data).filter(key => key === queryKey).reduce((result, key) => {
result[key] = `"${data[key]}"`;
return result;
},{}),
Object.keys(fields).reduce((result, key) => {
result[key] = types.string;
return result;
},{})
);
//console.log("listQuery string: ", query(queryObj));
return {
query:gql`${query(queryObj)}`,
context: context
}
};
export const getEntryQuery = ( entryId, data, fields, context={}) => {
//console.log("getEntryQuery: ", entryId, data, fields, context);
if (data == undefined) {
console.error("getEntryQuery requires a data argument");
return undefined;
}
if (Object.keys(data).length !== 2) {
console.error("getEntryQuery requires exact 2 fields provided in the data argument");
return undefined;
}
const queryObj = {};
queryObj[`get_${entryId}`] = params(
Object.keys(data).reduce((result, key) => {
result[key] = `"${data[key]}"`;
return result;
},{}),
Object.keys(fields).reduce((result, key) => {
result[key] = types.string;
return result;
},{})
);
//console.log("listQuery string: ", query(queryObj));
return {
query:gql`${query(queryObj)}`,
context: context
}
};
export const updateEntryQuery = ( entryId, callback, context={}) => {
return {entryId: entryId, callback: callback, context: context };
}
/**
* this function provides a executable graphql-query: "scan_{entryId}"
*
*/
export const getEntryScanQuery = ( entryId, data, fields, context={}) => {
//console.log("getEntryScanQuery: ", entryId, data, fields, context);
if (data == undefined) {
console.error("getEntryScanQuery requires a data argument, this may be empty");
return undefined;
}
const queryObj = {};
if (Object.keys(data).length > 0) {
const queryKey = Object.keys(data)[0];
queryObj[`scan_${entryId}_${queryKey}`] = params(
Object.keys(data).reduce((result, key) => {
// when we have an array at the key-pos in data, then we want to get a range
if (Array.isArray(data[key])) {
if (data[key].length > 0 && data[key][0] !== undefined) {
result[`start_${key}`] = `"${data[key][0]}"`;
}
if (data[key].length > 1 && data[key][1] !== undefined) {
result[`end_${key}`] = `"${data[key][1]}"`;
}
} else {
result[key] = `"${data[key]}"`;
}
return result;
},{}),
Object.keys(fields).reduce((result, key) => {
result[key] = types.string;
return result;
},{})
);
//console.log(gql`${query(queryObj)}`);
return {
query:gql`${query(queryObj)}`,
context: context
}
} else {
queryObj[`scan_${entryId}`] = params(
{scanall:`"yes"`},
Object.keys(fields).reduce((result, key) => {
result[key] = types.string;
return result;
},{})
);
//console.log(gql`${query(queryObj)}`);
return {
query:gql`${query(queryObj)}`,
context: context
}
}
//console.log("scanQuery string: ", query(queryObj));
};
export async function select (client, {query, context={}}) {
if (!context["userId"]) {
context["userId"] = new Cookies().get(IC_USER_ID);
}
//console.log("select: ", query, context);
return await client.query({
query: query,
context: context
}).then(result => {
//console.log("select result: ", result)
return result.data ? result.data : result;
}).catch(error => {
console.log(error);
});
};
/**
* uses this: https://github.com/acro5piano/typed-graphqlify
*
* TODO generalize to other data-types than string
*
* @param client
* @param entryId
* @param data
* @returns {any|Promise<T>|Promise<U>}
*/
export async function mutate (client, { mutation, context={}}) {
if (!context["userId"]) {
context["userId"] = new Cookies().get(IC_USER_ID);
}
//console.log("mutate: ", mutation, context);
//console.log("mutation string: ", mutation(mutationObj));
return await client.mutate({
mutation: mutation,
context: context
}).then(result => { /*console.log(result)*/}).catch(error => { console.log(error) });
};
/**
*
* @param client
* @param callback (oldData) => newData
* @param context
* @returns {Promise<any>}
*/
export async function update (client, { entryId, getEntryQuery, setEntryMutation}) {
const oldData = await select(
client,
getEntryQuery()
);
return await mutate(
client,
setEntryMutation(oldData[`get_${entryId}`])
);
};