forked from ivanbokii/dynochamber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery-builder.js
80 lines (61 loc) · 2.11 KB
/
query-builder.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
var _ = require('lodash');
var traverse = require('traverse');
var queryBuilder = {};
queryBuilder._addTableName = function(query, tableName) {
query.TableName = tableName;
return query;
};
queryBuilder._addDynamoOperation = function(query, operation) {
return _.merge(query, operation);
};
queryBuilder._stringHasPlaceholders = function(stringValue) {
const regex = /\{\{([a-zA-Z]\w*)\}\}/;
return _.isString(stringValue) && stringValue.match(regex) != null;
};
queryBuilder._stringIsPlaceholder = function(stringValue) {
const regex = /^\{\{([a-zA-Z]\w*)\}\}$/;
var match = regex.exec(stringValue);
if (match != null) {
return match[1];
}
return false;
};
queryBuilder._substitutePlaceholders = function(value, model) {
var replacementKey = queryBuilder._stringIsPlaceholder(value);
if (replacementKey) return model[replacementKey];
var regex = /\{\{([a-zA-Z]\w*)\}\}/g;
var match;
while ((match = regex.exec(value)) !== null) {
var keyName = match[1];
value = value.replace(new RegExp(`\{\{${keyName}\}\}`), model[keyName]);
regex = /\{\{([a-zA-Z]\w*)\}\}/g;
}
return value;
};
queryBuilder.cleanFromNonDynamoData = function(query) {
const nonDynamoFields = ["_type", "_validator", "_options"];
return _.omit(query, nonDynamoFields);
};
queryBuilder.fillPlaceholders = function(query, model) {
query = _.clone(query);
traverse(query).forEach(function(value) {
if (_.isFunction(value)) {
this.update(value(model));
}
if (queryBuilder._stringHasPlaceholders(value)) {
this.update(queryBuilder._substitutePlaceholders(value, model));
}
});
return query;
};
queryBuilder.build = function(tableName, operationTemplate, model) {
var table = _.isFunction(tableName) ? tableName() : tableName;
var buildDynamoQuery = _.flow(
_.partialRight(queryBuilder._addTableName, table),
_.partialRight(queryBuilder._addDynamoOperation, operationTemplate),
_.partialRight(queryBuilder.fillPlaceholders, model),
queryBuilder.cleanFromNonDynamoData);
var initialQuery = {};
return buildDynamoQuery(initialQuery);
};
module.exports = queryBuilder;