-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathupdate-expression-builder.ts
More file actions
196 lines (185 loc) · 6.97 KB
/
update-expression-builder.ts
File metadata and controls
196 lines (185 loc) · 6.97 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
/**
* @module expression
*/
import { Metadata } from '../../decorator/metadata/metadata'
import {
alterCollectionPropertyMetadataForSingleItem,
PropertyMetadata,
} from '../../decorator/metadata/property-metadata.model'
import { toDbOne } from '../../mapper/mapper'
import { AttributeType } from '../../mapper/type/attribute-type.type'
import { Attribute, Attributes } from '../../mapper/type/attribute.type'
import { getPropertyPath, isSet } from '../../mapper/util'
import { deepFilter } from './condition-expression-builder'
import { resolveAttributeNames } from './functions/attribute-names.function'
import { uniqueAttributeValueNameRecord } from './functions/unique-attribute-value-name.function'
import { UpdateActionDef } from './type/update-action-def'
import { UpdateAction } from './type/update-action.type'
import { UpdateExpression } from './type/update-expression.type'
/**
* 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} operation
* @param {any[]} values Depending on the operation the amount of values differs
* @param {Record<string, 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 buildUpdateExpression(
attributePath: string,
operation: UpdateActionDef,
values: any[],
existingValueNames: Record<string, string> | undefined,
metadata: Metadata<any> | undefined,
): UpdateExpression {
// get rid of undefined values
values = deepFilter(values, (value) => value !== undefined) || []
// 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 = uniqueAttributeValueNameRecord(attributePath, existingValueNames)
/*
* build the statement
*/
return buildDefaultExpression(
attributePath,
resolvedAttributeNames.placeholder,
valuePlaceholder,
resolvedAttributeNames.attributeNames,
values,
existingValueNames,
propertyMetadata,
operation,
)
}
/**
* @hidden
*/
function buildDefaultExpression(
attributePath: string,
namePlaceholder: string,
valuePlaceholder: string,
attributeNames: Record<string, string>,
values: any[],
_existingValueNames: Record<string, string> | undefined,
propertyMetadata: PropertyMetadata<any> | undefined,
operator: UpdateActionDef,
): UpdateExpression {
const attributeValues: Attributes<any> = {}
let attribute: Attribute | null = null
if (!isNoAttributeValueAction(operator.action)) {
// special cases: appendToList, add, removeFromSet
// we allow to provide arrays or sets for those methods.
// so it's necessary to make sure appendToList receives Arrays, add & removeFromSet receive Sets
if (['removeFromSet', 'add'].includes(operator.action) && Array.isArray(values[0])) {
values[0] = new Set(values[0])
} else if (['appendToList'].includes(operator.action) && isSet(values[0])) {
values[0] = [...values[0]]
}
// special case: [same as in buildDefaultConditionExpression]
// we have the metadata for an Array/Set of an Object,
// but only get a single item when using list indexes in attributePath
// e.g. `attribute('myCollectionProp[0]').set(...)`
// (not exclusive to `.set(...)` but all updateActions)
if (/\[\d+\]$/.test(attributePath)) {
attribute = toDbOne(
values[0],
getPropertyPath(propertyMetadata, attributePath),
alterCollectionPropertyMetadataForSingleItem(propertyMetadata),
)
} else {
attribute = toDbOne(values[0], propertyMetadata)
}
if (attribute) {
attributeValues[valuePlaceholder] = attribute
}
}
// see update-expression-definition-chain.ts for action definitions
let statement: string
switch (operator.action) {
case 'incrementBy':
validateAttributeType(operator.action, attribute, 'N')
statement = `${namePlaceholder} = ${namePlaceholder} + ${valuePlaceholder}`
break
case 'decrementBy':
validateAttributeType(operator.action, attribute, 'N')
statement = `${namePlaceholder} = ${namePlaceholder} - ${valuePlaceholder}`
break
case 'set':
if (values.length > 1 && !!values[values.length - 1] === true) {
statement = `${namePlaceholder} = if_not_exists(${namePlaceholder}, ${valuePlaceholder})`
} else {
statement = `${namePlaceholder} = ${valuePlaceholder}`
}
break
case 'appendToList':
if (values.length > 1 && values[values.length - 1] === 'START') {
statement = `${namePlaceholder} = list_append(${valuePlaceholder}, ${namePlaceholder})`
} else {
statement = `${namePlaceholder} = list_append(${namePlaceholder}, ${valuePlaceholder})`
}
break
case 'remove':
statement = `${namePlaceholder}`
break
case 'removeFromListAt':
statement = values.map((pos) => `${namePlaceholder}[${pos}]`).join(', ')
break
case 'add':
validateAttributeType(operator.action, attribute, 'N', 'SS', 'NS', 'BS')
statement = `${namePlaceholder} ${valuePlaceholder}`
break
case 'removeFromSet':
validateAttributeType(operator.action, attribute, 'SS', 'NS', 'BS')
statement = `${namePlaceholder} ${valuePlaceholder}`
break
default:
throw new Error(`no implementation for action ${operator.action}`)
}
return {
type: operator.actionKeyword,
statement,
attributeNames,
attributeValues,
}
}
/**
* @hidden
*/
function isNoAttributeValueAction(action: UpdateAction) {
return (
action === 'remove' ||
// special cases: values are used in statement instead of expressionValues
action === 'removeFromListAt'
)
}
/**
* @hidden
*/
export function validateAttributeType(name: string, attribute: Attribute | null, ...allowedTypes: AttributeType[]) {
if (attribute === null || attribute === undefined) {
throw new Error(`${name} requires an attributeValue of ${allowedTypes.join(', ')} but non was given`)
}
const key = <AttributeType>Object.keys(attribute)[0]
if (!allowedTypes.includes(key)) {
throw new Error(
`Type ${key} of ${JSON.stringify(attribute)} is not allowed for ${name}. Valid types are: ${allowedTypes.join(
'. ',
)}`,
)
}
}