-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUpdateExpression.ts
84 lines (69 loc) · 2.41 KB
/
UpdateExpression.ts
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
import ExpressionAttributeValues from './ExpressionAttributeValues'
export type ExpressionType = 'ADD' | 'DELETE' | 'REMOVE' | 'SET'
interface ITransaction { keyName: string; value?: any }
export default (exprAttrValues: ReturnType<typeof ExpressionAttributeValues>) => {
const adds: ITransaction[] = []
const deletes: ITransaction[] = []
const removes: ITransaction[] = []
const sets: ITransaction[] = []
return {
add: (type: ExpressionType, keyName: string, value?: any) => {
const newTransaction: ITransaction = { keyName, value }
switch (type) {
case 'ADD':
adds.push(newTransaction)
break
case 'DELETE':
deletes.push(newTransaction)
break
case 'REMOVE':
removes.push(newTransaction)
break
case 'SET':
sets.push(newTransaction)
break
}
return this
},
// Looking to clean this up, but the slight differences between the expressions make it difficult
get: () => {
const compiledTransactions = []
const mappedAdds = adds.map((add, index) => {
const transactionIndex = `:Add${index + 1}`
exprAttrValues.add(transactionIndex, add.value)
return `${add.keyName} ${transactionIndex}`
})
if (mappedAdds.length > 0) {
compiledTransactions.push(`ADD ${mappedAdds.join(', ')}`)
}
const mappedDeletes = deletes.map((del, index) => {
const transactionIndex = `:Delete${index + 1}`
exprAttrValues.add(transactionIndex, del.value)
return `${del.keyName} ${transactionIndex}`
})
if (mappedDeletes.length > 0) {
compiledTransactions.push(`DELETE ${mappedDeletes.join(', ')}`)
}
const mappedRemoves = removes.map((remove) => {
return remove.keyName
})
if (mappedRemoves.length > 0) {
compiledTransactions.push(`REMOVE ${mappedRemoves.join(', ')}`)
}
const mappedSets = sets.map((set, index) => {
const transactionIndex = `:Set${index + 1}`
exprAttrValues.add(transactionIndex, set.value)
return `${set.keyName} = ${transactionIndex}`
})
if (mappedSets.length > 0) {
compiledTransactions.push(`SET ${mappedSets.join(', ')}`)
}
if (compiledTransactions.length !== 0) {
return {
UpdateExpression: compiledTransactions.join(' ')
}
}
return {}
}
}
}