-
Notifications
You must be signed in to change notification settings - Fork 1
/
dbconn.js
123 lines (107 loc) · 3.7 KB
/
dbconn.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
111
112
113
114
115
116
117
118
119
120
121
122
123
(function () {
var aws = require("aws-sdk");
var config = require("./config.js")
aws.config.update(config);
var dynamoDB = new aws.DynamoDB.DocumentClient();
var TABLENAME = "Books";
exports.query = function (key) {
var params = {
TableName: TABLENAME
};
if (key) {
params.FilterExpression = "contains(title, :title) OR contains(subtitle, :subtitle) \
OR contains(author, :author) OR contains(description, :desc)";
params.ExpressionAttributeValues = {
":title": key,
":subtitle": key,
":author": key,
":desc": key
};
}
return new Promise(function (resolve, reject) {
dynamoDB.scan(params, function (err, dbBooks) {
if (err) {
reject(err);
return;
}
if (!dbBooks || !dbBooks.Items || dbBooks.Items.length === 0) {
reject("No books found in the DB");
return;
}
resolve(dbBooks.Items);
});
});
}
exports.getItem = function (key) {
var params = {
TableName: TABLENAME
};
params.KeyConditionExpression = "isbn=:isbn";
params.ExpressionAttributeValues = {
":isbn": key
};
return new Promise(function (resolve, reject) {
if (!key || key === "") {
reject("The provided key is invalid");
}
dynamoDB.query(params, function (err, dbBooks) {
if (err) {
console.log(err);
reject(err);
return;
}
if (!dbBooks || !dbBooks.Items || dbBooks.Items.length !== 1) {
reject("Key " + key + " was not found");
return;
}
resolve(dbBooks.Items[0]);
});
});
}
exports.update = function (isbn, newBook) {
console.log("Updating book ", isbn, " to new value: ", newBook);
return new Promise(function (resolve, reject) {
var params = {
TableName: TABLENAME,
Key: {
"isbn": isbn
}
};
var attributeUpdates = {};
for (var attr in newBook) {
if (attr !== "isbn") {
attributeUpdates[attr] = {
Action: "PUT",
Value: newBook[attr]
}
}
}
params["AttributeUpdates"] = attributeUpdates;
dynamoDB.update(params, function (err, data) {
if (err) {
reject(err);
return;
}
resolve();
})
});
}
exports.createObj = function (book) {
console.log("Creating and adding new book ", book.title, " with quantity ", book.quantity, ", price ", book.price);
// Convert the book model into a suitable representation for DynamoDB
var params = {
"TableName": TABLENAME,
"Item": book
}
return new Promise(function (resolve, reject) {
dynamoDB.put(params, function (err) {
if (err) {
console.log(err);
reject(err);
return;
}
resolve();
})
});
}
}());