-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
85 lines (69 loc) · 1.89 KB
/
index.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
'use strict';
const databaseManager = require('./databaseManager');
const uuidv1 = require('uuid/v1');
exports.productHandler = function(event, context, callback){
console.log(event, context);
switch (event.httpMethod) {
case 'DELETE':
deleteItem(event, callback);
break;
case 'GET':
getItem(event, callback);
break;
case 'POST':
saveItem(event, callback);
break;
case 'PUT':
updateItem(event, callback);
break;
default:
sendResponse(404, `Unsupported method "${event.httpMethod}"`, callback);
}
};
function saveItem(event, callback) {
const item = JSON.parse(event.body);
item.productId = uuidv1();
databaseManager.saveItem(item).then(response => {
console.log(response);
sendResponse(200, item.productId, callback);
}, (reject) =>{
sendResponse(400, reject, callback);
});
}
function getItem(event, callback) {
const itemId = event.pathParameters.productId;
databaseManager.getItem(itemId).then(response => {
console.log(response);
if(response)
sendResponse(200, response, callback);
else
sendResponse(404, "Please passa valid productId", callback);
},(reject) =>{
sendResponse(400, reject, callback);
});
}
function deleteItem(event, callback) {
const itemId = event.pathParameters.productId;
databaseManager.deleteItem(itemId).then(response => {
sendResponse(200, 'DELETE ITEM', callback);
}, (reject) => {
sendResponse(400, reject, callback);
});
}
function updateItem(event, callback) {
const itemId = event.pathParameters.productId;
const body = JSON.parse(event.body);
databaseManager.updateItem(itemId, body).then(response => {
console.log(response);
sendResponse(200, response, callback);
}, (reject) => {
sendResponse(400, reject, callback);
});
}
function sendResponse(statusCode, message, callback) {
const response = {
statusCode: statusCode,
body: JSON.stringify(message)
};
callback(null, response);
}