forked from aws-samples/aws-serverless-workshops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtickets-post.js
62 lines (49 loc) · 1.86 KB
/
tickets-post.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
'use strict';
const AWS = require("aws-sdk");
const table = process.env.TABLE_NAME;
/**
* This will handle posting of new ticket and puts for updates.
* if incoming ticket has a non-zero id value its assumed to be an update
* request to an existing ticket entity.
*
* @param event
* @param context
* @param callback
*/
exports.handler = (event, context, callback) => {
console.log('Received event:', JSON.stringify(event, null, 2));
let body = JSON.parse(event.body);
const docClient = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: table, //we get table name from env variable.
Item: {
"id": new Date().toISOString(),
"description": body.description,
"assigned": body.assigned,
"priority": body.priority,
"status": body.status,
"createdBy": body.createdBy,
"createdOn": new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
}
};
console.log("Adding a new ticket..." + JSON.stringify(params));
docClient.put(params, function (err, data) {
if (err) {
console.error("Unable to add ticket. Error JSON:", JSON.stringify(err, null, 2));
this.statusCode = '500';
callback("Unable to add ticket");
} else {
console.log("Added ticket:", JSON.stringify(data, null, 2));
this.statusCode = '200';
const response = {
statusCode: this.statusCode,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify(params.Item)
};
callback(null, response);
}
});
};