forked from jed/dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Update.js
110 lines (83 loc) · 2.24 KB
/
Update.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
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
var Predicates = require("./Predicates")
, Attributes = require("./Attributes")
, Value = require("./Value")
function Update(table, database) {
this.TableName = table
Object.defineProperty(
this, "database",
{value: database, enumerable: false}
)
}
Update.prototype = {
when: function(name, operator, value) {
var predicates = new Predicates(name, operator, value)
, expectation = this.Expected = {}
, names = Object.keys(predicates)
if (names.length > 1) {
throw new Error("Only one condition allowed per expectation.")
}
name = names[0]
operator = predicates[name].ComparisonOperator
value = predicates[name].AttributeValueList[0]
switch (operator) {
case "NULL":
expectation[name] = {Exists: false}
return this
case "NOT_NULL":
expectation[name] = {Exists: true}
return this
case "EQ":
expectation[name] = {Value: value}
return this
}
throw new Error("Invalid expectation: " + [name, operator, value])
},
returning: function(constant) {
this.ReturnValues = constant
return this
},
update: function(action, key, value) {
var updates = this.AttributeUpdates || (this.AttributeUpdates = {})
if (updates[key]) {
throw new Error("Attribute '" + key + "' cannot be updated more than once.")
}
updates[key] = {Action: action}
if (value != null) updates[key].Value = Value(value)
return this
},
put: function(key, value) {
return this.update("PUT", key, value)
},
add: function(key, value) {
return this.update("ADD", key, value)
},
remove: function(key, value) {
return this.update("DELETE", key, value)
},
save: function(cb) {
if (this.Item) {
this.database.request(
"PutItem",
this,
function(err, data) {
if (err) return cb(err)
if (data = data.Attributes) {
cb(null, Attributes.prototype.parse(data))
}
else cb()
}
)
return this
}
if (this.AttributeUpdates) {
this.database.request(
"UpdateItem",
this,
cb
)
return this
}
throw new Error("Nothing to save.")
}
}
module.exports = Update