-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcondition-expression-builder.ts
More file actions
399 lines (365 loc) · 12.4 KB
/
condition-expression-builder.ts
File metadata and controls
399 lines (365 loc) · 12.4 KB
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
/**
* @module expression
*/
import { Metadata } from '../../decorator/metadata/metadata'
import {
alterCollectionPropertyMetadataForSingleItem,
PropertyMetadata,
} from '../../decorator/metadata/property-metadata.model'
import { curry } from '../../helper/curry.function'
import { isPlainObject } from '../../helper/is-plain-object.function'
import { toDbOne } from '../../mapper/mapper'
import { Attribute, Attributes } from '../../mapper/type/attribute.type'
import { typeOf } from '../../mapper/util'
import { resolveAttributeNames } from './functions/attribute-names.function'
import { isFunctionOperator } from './functions/is-function-operator.function'
import { isNoParamFunctionOperator } from './functions/is-no-param-function-operator.function'
import { operatorParameterArity } from './functions/operator-parameter-arity.function'
import { uniqueAttributeValueName } from './functions/unique-attribute-value-name.function'
import { ConditionOperator } from './type/condition-operator.type'
import { Expression } from './type/expression.type'
import { validateAttributeType } from './update-expression-builder'
import { dynamicTemplate } from './util'
/**
* @hidden
*/
type BuildFilterFn = (
attributePath: string,
namePlaceholder: string,
valuePlaceholder: string,
attributeNames: Record<string, string>,
values: any[],
existingValueNames: string[] | undefined,
propertyMetadata: PropertyMetadata<any> | undefined,
) => Expression
/**
* see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
* https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html
*/
/**
* Will walk the object tree recursively and removes all items which do not satisfy the filterFn
* @param obj
* @param {(value: any) => boolean} filterFn
* @returns {any}
* @hidden
*/
export function deepFilter(obj: any, filterFn: (value: any) => boolean): any {
if (Array.isArray(obj)) {
const returnArr: any[] = []
obj.forEach((i) => {
const item = deepFilter(i, filterFn)
if (item !== undefined) {
returnArr.push(item)
}
})
return returnArr
} else if (obj instanceof Set) {
const returnArr: any[] = []
Array.from(obj).forEach((i) => {
const item = deepFilter(i, filterFn)
if (item !== undefined) {
returnArr.push(item)
}
})
return new Set(returnArr)
} else if (isPlainObject(obj)) {
const returnObj: Record<string, any> = {}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key]
const item = deepFilter(value, filterFn)
if (item !== undefined) {
returnObj[key] = item
}
}
}
return returnObj
} else {
if (filterFn(obj)) {
return obj
} else {
return undefined
}
}
}
/**
* Will create a condition which can be added to a request using the param object.
* It will create the expression statement and the attribute names and values.
*
* @param {string} attributePath
* @param {ConditionOperator} operator
* @param {any[]} values Depending on the operator the amount of values differs
* @param {string[]} existingValueNames If provided the existing names are used to make sure we have a unique name for the current attributePath
* @param {Metadata<any>} metadata If provided we use the metadata to define the attribute name and use it to map the given value(s) to attributeValue(s)
* @returns {Expression}
* @hidden
*/
export function buildFilterExpression(
attributePath: string,
operator: ConditionOperator,
values: any[],
existingValueNames: string[] | undefined,
metadata: Metadata<any> | undefined,
): Expression {
// metadata get rid of undefined values
values = deepFilter(values, (value) => value !== undefined)
// check if provided values are valid for given operator
validateForOperator(operator, values)
// load property metadata if model metadata was provided
let propertyMetadata: PropertyMetadata<any> | undefined
if (metadata) {
propertyMetadata = metadata.forProperty(attributePath)
}
/*
* resolve placeholder and valuePlaceholder names (same as attributePath if it not already exists)
* myProp -> #myProp for name placeholder and :myProp for value placeholder
*
* person[0] -> #person: person
* person.list[0].age -> #person: person, #attr: attr, #age: age
* person.age
*/
const resolvedAttributeNames = resolveAttributeNames(attributePath, metadata)
const valuePlaceholder = uniqueAttributeValueName(attributePath, existingValueNames)
/*
* build the statement
*/
let buildFilterFn: BuildFilterFn
switch (operator) {
case 'IN':
buildFilterFn = buildInConditionExpression
break
case 'BETWEEN':
buildFilterFn = buildBetweenConditionExpression
break
default:
buildFilterFn = curry(buildDefaultConditionExpression)(operator)
}
return buildFilterFn(
attributePath,
resolvedAttributeNames.placeholder,
valuePlaceholder,
resolvedAttributeNames.attributeNames,
values,
existingValueNames,
propertyMetadata,
)
}
/**
* IN expression is unlike all the others property the operand is an array of unwrapped values (not attribute values)
*
* @param {string} attributePath
* @param {string[]} values
* @param {string[]} existingValueNames
* @param {PropertyMetadata<any>} propertyMetadata
* @returns {Expression}
* @hidden
*/
function buildInConditionExpression(
_attributePath: string,
namePlaceholder: string,
valuePlaceholder: string,
attributeNames: Record<string, string>,
values: any[],
_existingValueNames: string[] | undefined,
propertyMetadata: PropertyMetadata<any> | undefined,
): Expression {
const attributeValues: Attributes<any> = (<any[]>values[0])
.map((value) => toDbOne(value, propertyMetadata))
.reduce((result, mappedValue: Attribute | null, index: number) => {
if (mappedValue !== null) {
validateAttributeType('IN condition', mappedValue, 'S', 'N', 'B')
result[`${valuePlaceholder}_${index}`] = mappedValue
}
return result
}, <Attributes<any>>{})
const inStatement = (<any[]>values[0]).map((_value: any, index: number) => `${valuePlaceholder}_${index}`).join(', ')
return {
statement: `${namePlaceholder} IN (${inStatement})`,
attributeNames,
attributeValues,
}
}
/**
* @hidden
*/
function buildBetweenConditionExpression(
attributePath: string,
namePlaceholder: string,
valuePlaceholder: string,
attributeNames: Record<string, string>,
values: string[],
existingValueNames: string[] | undefined,
propertyMetadata: PropertyMetadata<any> | undefined,
): Expression {
const attributeValues: Attributes<any> = {}
const mappedValue1 = toDbOne(values[0], propertyMetadata)
const mappedValue2 = toDbOne(values[1], propertyMetadata)
if (mappedValue1 === null || mappedValue2 === null) {
throw new Error('make sure to provide an actual value for te BETWEEN operator')
}
;[mappedValue1, mappedValue2].forEach((mv) => validateAttributeType('between', mv, 'S', 'N', 'B'))
const value2Placeholder = uniqueAttributeValueName(attributePath, [valuePlaceholder].concat(existingValueNames || []))
const statement = `${namePlaceholder} BETWEEN ${valuePlaceholder} AND ${value2Placeholder}`
attributeValues[valuePlaceholder] = mappedValue1
attributeValues[value2Placeholder] = mappedValue2
return {
statement,
attributeNames,
attributeValues,
}
}
/**
* @hidden
*/
function buildDefaultConditionExpression(
operator: ConditionOperator,
_attributePath: string,
namePlaceholder: string,
valuePlaceholder: string,
attributeNames: Record<string, string>,
values: any[],
_exisingValueNames: string[] | undefined,
propertyMetadata: PropertyMetadata<any> | undefined,
): Expression {
let statement: string
let hasValue = true
if (isFunctionOperator(operator)) {
if (isNoParamFunctionOperator(operator)) {
statement = `${operator} (${namePlaceholder})`
hasValue = false
} else {
statement = `${operator} (${namePlaceholder}, ${valuePlaceholder})`
}
} else {
statement = [namePlaceholder, operator, valuePlaceholder].join(' ')
}
const attributeValues: Attributes<any> = {}
if (hasValue) {
let attribute: Attribute | null
if (operator === 'contains' || operator === 'not_contains') {
attribute = toDbOne(values[0], alterCollectionPropertyMetadataForSingleItem(propertyMetadata))
validateAttributeType(`${operator} condition`, attribute, 'N', 'S', 'B')
} else {
attribute = toDbOne(values[0], propertyMetadata)
switch (operator) {
case 'begins_with':
validateAttributeType(`${operator} condition`, attribute, 'S', 'B')
break
case '<':
case '<=':
case '>':
case '>=':
validateAttributeType(`${operator} condition`, attribute, 'N', 'S', 'B')
break
}
}
if (attribute) {
attributeValues[valuePlaceholder] = attribute
}
}
return {
statement,
attributeNames,
attributeValues,
}
}
/**
* Every operator requires a predefined arity of parameters, this method checks for the correct arity and throws an Error
* if not correct
*
* @param operator
* @param values The values which will be applied to the operator function implementation, not every operator requires values
* @throws {Error} error Throws an error if the amount of values won't match the operator function parameter arity or
* the given values is not an array
* @hidden
*/
function validateForOperator(operator: ConditionOperator, values?: any[]) {
validateArity(operator, values)
/*
* validate values if operator supports values
*/
if (!isFunctionOperator(operator) || (isFunctionOperator(operator) && !isNoParamFunctionOperator(operator))) {
if (values && Array.isArray(values) && values.length) {
validateValues(operator, values)
} else {
throw new Error(
dynamicTemplate(ERR_ARITY_DEFAULT, { parameterArity: operatorParameterArity(operator), operator }),
)
}
}
}
// tslint:disable:no-invalid-template-strings
/*
* error messages for arity issues
*/
/**
* @hidden
*/
export const ERR_ARITY_IN =
'expected ${parameterArity} value(s) for operator ${operator}, this is not the right amount of method parameters for this operator (IN operator requires one value of array type)'
/**
* @hidden
*/
export const ERR_ARITY_DEFAULT =
'expected ${parameterArity} value(s) for operator ${operator}, this is not the right amount of method parameters for this operator'
// tslint:enable:no-invalid-template-strings
/**
* @hidden
*/
function validateArity(operator: ConditionOperator, values?: any[]) {
if (values === null || values === undefined) {
if (isFunctionOperator(operator) && !isNoParamFunctionOperator(operator)) {
// the operator needs some values to work
throw new Error(
dynamicTemplate(ERR_ARITY_DEFAULT, { parameterArity: operatorParameterArity(operator), operator }),
)
}
} else if (values && Array.isArray(values)) {
const parameterArity = operatorParameterArity(operator)
// check for correct amount of values
if (values.length !== parameterArity) {
switch (operator) {
case 'IN':
throw new Error(dynamicTemplate(ERR_ARITY_IN, { parameterArity, operator }))
default:
throw new Error(dynamicTemplate(ERR_ARITY_DEFAULT, { parameterArity, operator }))
}
}
}
}
/*
* error message for wrong operator values
*/
// tslint:disable:no-invalid-template-strings
/**
* @hidden
*/
export const ERR_VALUES_BETWEEN_TYPE =
'both values for operator BETWEEN must have the same type, got ${value1} and ${value2}'
/**
* @hidden
*/
export const ERR_VALUES_IN = 'the provided value for IN operator must be an array'
// tslint:enable:no-invalid-template-strings
/**
* Every operator has some constraints about the values it supports, this method makes sure everything is fine for given
* operator and values
* @hidden
*/
function validateValues(operator: ConditionOperator, values: any[]) {
// some additional operator dependent validation
switch (operator) {
case 'BETWEEN':
// values must be the same type
if (typeOf(values[0]) !== typeOf(values[1])) {
throw new Error(
dynamicTemplate(ERR_VALUES_BETWEEN_TYPE, { value1: typeOf(values[0]), value2: typeOf(values[1]) }),
)
}
break
case 'IN':
if (!Array.isArray(values[0])) {
throw new Error(ERR_VALUES_IN)
}
}
}