-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathprepare-and-add-update-expressions.function.ts
More file actions
63 lines (57 loc) · 2.22 KB
/
prepare-and-add-update-expressions.function.ts
File metadata and controls
63 lines (57 loc) · 2.22 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
/**
* @module expression
*/
import * as DynamoDB from '@aws-sdk/client-dynamodb'
import { Metadata } from '../../decorator/metadata/metadata'
import { Attributes } from '../../mapper/type/attribute.type'
import { addUpdateExpression } from './param-util'
import { Expression } from './type/expression.type'
import { UpdateActionKeyword } from './type/update-action-keyword.type'
import { UpdateExpressionDefinitionFunction } from './type/update-expression-definition-function'
import { UpdateExpression } from './type/update-expression.type'
/**
* @hidden
*/
export function prepareAndAddUpdateExpressions(
metadata: Metadata<any>,
params: DynamoDB.UpdateItemInput | DynamoDB.Update,
updateDefFns: UpdateExpressionDefinitionFunction[],
) {
if (updateDefFns && updateDefFns.length) {
const sortedByActionKeyWord: Map<UpdateActionKeyword, UpdateExpression[]> = updateDefFns
.map((updateDefFn) => {
// TODO post-v3:: investigate on how to remove any
return updateDefFn(params.ExpressionAttributeNames, metadata)
})
.reduce((result, expr) => {
const actionKeyword = expr.type
if (!result.has(actionKeyword)) {
result.set(actionKeyword, [])
}
result.get(actionKeyword).push(expr)
return result
}, new Map())
const actionStatements: string[] = []
let attributeValues: Attributes = {}
let attributeNames: Record<string, string> = {}
for (const [actionKeyword, updateExpressions] of sortedByActionKeyWord) {
const statements: string[] = []
if (updateExpressions && updateExpressions.length) {
updateExpressions.forEach((updateExpression) => {
statements.push(updateExpression.statement)
attributeValues = { ...attributeValues, ...updateExpression.attributeValues }
attributeNames = { ...attributeNames, ...updateExpression.attributeNames }
})
actionStatements.push(`${actionKeyword} ${statements.join(', ')}`)
}
}
const expression: Expression = {
statement: actionStatements.join(' '),
attributeValues,
attributeNames,
}
addUpdateExpression(expression, params)
} else {
throw new Error('at least one update operation must be defined')
}
}