-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
349 lines (308 loc) · 9.68 KB
/
index.js
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
import { v4 as uuidv4 } from 'uuid';
import { toJsonObject } from './rds/index.js'
export const dynamodbUtils = {
toDynamoDB: function(value) {
if (typeof (value) === "number") {
return this.toNumber(value);
} else if (typeof (value) === "string") {
return this.toString(value);
} else if (typeof (value) === "boolean") {
return this.toBoolean(value);
} else if (typeof (value) === "object") {
if (value.length !== undefined) {
return this.toList(value);
} else {
return this.toMap(value);
}
} else {
throw new Error(`Not implemented for ${value}`);
}
},
toString: function(value) {
if (value === null) { return null; };
return { S: value };
},
toStringSet: function(value) {
if (value === null) { return null; };
return { SS: value };
},
toNumber: function(value) {
if (value === null) { return null; };
return { N: value };
},
toNumberSet: function(value) {
if (value === null) { return null; };
return { NS: value };
},
toBinary: function(value) {
if (value === null) { return null; };
return { B: value };
},
toBinarySet: function(value) {
if (value === null) { return null; };
return { BS: value };
},
toBoolean: function(value) {
if (value === null) { return null; };
return { BOOL: value };
},
toNull: function() {
return { NULL: null };
},
toList: function(values) {
let out = [];
for (const value of values) {
out.push(this.toDynamoDB(value));
}
return { L: out }
},
toMap: function(mapping) {
return { M: this.toMapValues(mapping) };
},
toMapValues: function(mapping) {
let out = {};
for (const [k, v] of Object.entries(mapping)) {
out[k] = this.toDynamoDB(v);
}
return out;
},
toS3Object: function(key, bucket, region, version) {
let payload;
if (version === undefined) {
payload = {
s3: {
key,
bucket,
region,
}
};
} else {
payload = {
s3: {
key,
bucket,
region,
version,
}
};
};
return this.toString(JSON.stringify(payload));
},
fromS3ObjectJson: function(value) {
throw new Error("not implemented");
},
}
const FILTER_CONTAINS = "contains";
export const util = {
autoId: function() {
return uuidv4();
},
appendError: function(message, errorType, data, errorInfo) {
// This will be handled in LocalStack in a side channel by printing to stderr
console.error({ message, errorType, data, errorInfo });
},
time: {
nowFormatted: function(pattern) {
// TODO: not completely correct, but close enough probably
return new Date().toISOString();
},
nowISO8601: function() {
return new Date().toISOString();
},
},
transform: {
toDynamoDBFilterExpression: function(value) {
const items = Object.entries(value);
if (items.length != 1) {
throw new Error("invalid structure, should have one entry");
}
const [key, filter] = items[0];
const filterItems = Object.entries(filter);
if (filterItems.length !== 1) {
throw new Error("invalid structure, should have one filter expression");
}
const [filterType, contents] = filterItems[0];
const expressionName = `#${key}`;
const expressionValue = `:${key}_${filterType}`;
let expression;
let expressionNames = {};
let expressionValues = {};
switch (filterType) {
case FILTER_CONTAINS:
expression = `(contains(${expressionName},${expressionValue}))`;
expressionNames[expressionName] = key;
expressionValues[expressionValue] = util.dynamodb.toDynamoDB(contents);
break;
default:
throw new Error(`Not implemented for ${filterType}`);
}
return JSON.stringify({ expression, expressionNames, expressionValues });
},
toDynamoDBConditionExpression(condition) {
const result = generateFilterExpression(condition);
return JSON.stringify({
expression: result.expressions.join(' ').trim(),
expressionNames: result.expressionNames,
// upstream is missing this value: https://github.com/aws-amplify/amplify-cli/blob/5cc1b556d8081421dc68ee264dac02d5660ffee7/packages/amplify-appsync-simulator/src/velocity/util/transform/index.ts#L11
expressionValues: result.expressionValues,
});
},
},
dynamodb: dynamodbUtils,
rds: { toJsonObject },
};
// embedded here because imports don't yet work
const OPERATOR_MAP = {
ne: '<>',
eq: '=',
lt: '<',
le: '<=',
gt: '>',
ge: '>=',
in: 'contains',
};
const FUNCTION_MAP = {
contains: 'contains',
notContains: 'NOT contains',
beginsWith: 'begins_with',
};
export function generateFilterExpression(filter, prefix, parent) {
const expr = Object.entries(filter).reduce(
(sum, [name, value]) => {
let subExpr = {
expressions: [],
expressionNames: {},
expressionValues: {},
};
const fieldName = createExpressionFieldName(parent);
const filedValueName = createExpressionValueName(parent, name, prefix);
switch (name) {
case 'or':
case 'and': {
const JOINER = name === 'or' ? 'OR' : 'AND';
if (Array.isArray(value)) {
subExpr = scopeExpression(
value.reduce((expr, subFilter, idx) => {
const newExpr = generateFilterExpression(subFilter, [prefix, name, idx].filter((i) => i !== null).join('_'));
return merge(expr, newExpr, JOINER);
}, subExpr),
);
} else {
subExpr = generateFilterExpression(value, [prefix, name].filter((val) => val !== null).join('_'));
}
break;
}
case 'not': {
subExpr = scopeExpression(generateFilterExpression(value, [prefix, name].filter((val) => val !== null).join('_')));
subExpr.expressions.unshift('NOT');
break;
}
case 'between': {
const expr1 = createExpressionValueName(parent, 'between_1', prefix);
const expr2 = createExpressionValueName(parent, 'between_2', prefix);
const exprName = createExpressionName(parent);
const subExprExpr = `${createExpressionFieldName(parent)} BETWEEN ${expr1} AND ${expr2}`;
const exprValues = {
...createExpressionValue(parent, 'between_1', value[0], prefix),
...createExpressionValue(parent, 'between_2', value[1], prefix),
};
subExpr = {
expressions: [subExprExpr],
expressionNames: exprName,
expressionValues: exprValues,
};
break;
}
case 'ne':
case 'eq':
case 'gt':
case 'ge':
case 'lt':
case 'le': {
const operator = OPERATOR_MAP[name];
subExpr = {
expressions: [`(${fieldName} ${operator} ${filedValueName})`],
expressionNames: createExpressionName(parent),
expressionValues: createExpressionValue(parent, name, value, prefix),
};
break;
}
case 'attributeExists': {
const existsName = value === true ? 'attribute_exists' : 'attribute_not_exists';
subExpr = {
expressions: [`(${existsName}(${fieldName}))`],
expressionNames: createExpressionName(parent),
expressionValues: [],
};
break;
}
case 'contains':
case 'notContains':
case 'beginsWith': {
const functionName = FUNCTION_MAP[name];
subExpr = {
expressions: [`(${functionName}(${fieldName}, ${filedValueName}))`],
expressionNames: createExpressionName(parent),
expressionValues: createExpressionValue(parent, name, value, prefix),
};
break;
}
case 'in': {
const operatorName = OPERATOR_MAP[name];
subExpr = {
expressions: [`(${operatorName}(${filedValueName}, ${fieldName}))`],
expressionNames: createExpressionName(parent),
expressionValues: createExpressionValue(parent, name, value, prefix),
};
break;
}
default:
subExpr = scopeExpression(generateFilterExpression(value, prefix, name));
}
return merge(sum, subExpr);
},
{
expressions: [],
expressionNames: {},
expressionValues: {},
},
);
return expr;
}
function merge(expr1, expr2, joinCondition = 'AND') {
if (!expr2.expressions.length) {
return expr1;
}
const res = {
expressions: [...expr1.expressions, expr1.expressions.length ? joinCondition : '', ...expr2.expressions],
expressionNames: { ...expr1.expressionNames, ...expr2.expressionNames },
expressionValues: { ...expr1.expressionValues, ...expr2.expressionValues },
};
return res;
}
function createExpressionValueName(fieldName, op, prefix) {
return `:${[prefix, fieldName, op].filter((name) => name).join('_')}`;
}
function createExpressionName(fieldName) {
return {
[createExpressionFieldName(fieldName)]: fieldName,
};
}
function createExpressionFieldName(fieldName) {
return `#${fieldName}`;
}
function createExpressionValue(fieldName, op, value, prefix) {
const exprName = createExpressionValueName(fieldName, op, prefix);
const exprValue = dynamodbUtils.toDynamoDB(value);
return {
[`${exprName}`]: exprValue,
};
}
function scopeExpression(expr) {
const result = { ...expr };
result.expressions = result.expressions.filter((e) => !!e);
if (result.expressions.length > 1) {
result.expressions = ['(' + result.expressions.join(' ') + ')'];
}
return result;
}