-
Notifications
You must be signed in to change notification settings - Fork 5
/
delete-place.js
105 lines (94 loc) · 3.42 KB
/
delete-place.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
'use strict'
const AWS = require('aws-sdk')
AWS.config.update({ region: process.env.Region, apiVersion: '2012-08-10' })
if (process.env.AWS_SAM_LOCAL) AWS.config.update({ dynamodb: { endpoint: process.env.DynamoDbEndpoint } })
const docClient = new AWS.DynamoDB.DocumentClient()
const s3 = new AWS.S3({
apiVersion: '2006-03-01',
signatureVersion: 'v4',
Bucket: process.env.UploadPictureBucket,
})
module.exports.handler = async (event) => {
try {
const body = typeof event.body !== 'undefined' ? JSON.parse(event.body) : event
const { placeKey } = body
if (!placeKey) {
console.warn("placeKey not specified")
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({
status: 'error',
message: 'Please specify a place to delete'
})
}
}
try {
const { Item } = await docClient.get({ TableName: 'places', Key: { placeKey } }).promise()
const place = Item
if (place.picture) {
try {
const pictureParams = {
Bucket: process.env.UploadPictureBucket,
Key: place.picture
}
await s3.deleteObject(pictureParams).promise()
await deletePlace(placeKey)
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({
status: 'success',
})
}
} catch (err) {
console.error(err)
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({
status: 'error',
})
}
}
}
await deletePlace(placeKey)
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'success' })
}
} catch(err) {
console.error(err)
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({
status: 'error',
message: err.message,
placeKey
})
}
}
} catch (err) {
return {
statusCode: 200,
headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' },
body: JSON.stringify({
status: 'error',
message: err.message
})
}
}
}
async function deletePlace(placeKey) {
try {
const params = {
TableName: "places",
Key: { "placeKey": placeKey }
}
await docClient.delete(params).promise()
} catch (err) {
console.error(err)
}
}