This repository has been archived by the owner on Aug 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
createImage.ts
93 lines (79 loc) · 2.12 KB
/
createImage.ts
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
import { APIGatewayProxyHandler, APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'
import 'source-map-support/register'
import * as AWS from 'aws-sdk'
import * as uuid from 'uuid'
const docClient = new AWS.DynamoDB.DocumentClient()
const s3 = new AWS.S3({
signatureVersion: 'v4'
})
const groupsTable = process.env.GROUPS_TABLE
const imagesTable = process.env.IMAGES_TABLE
const bucketName = process.env.IMAGES_S3_BUCKET
const urlExpiration = process.env.SIGNED_URL_EXPIRATION
export const handler: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
console.log('Caller event', event)
const groupId = event.pathParameters.groupId
const validGroupId = await groupExists(groupId)
if (!validGroupId) {
return {
statusCode: 404,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
error: 'Group does not exist'
})
}
}
const imageId = uuid.v4()
const newItem = await createImage(groupId, imageId, event)
const url = getUploadUrl(imageId)
return {
statusCode: 201,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
newItem: newItem,
uploadUrl: url
})
}
}
async function groupExists(groupId: string) {
const result = await docClient
.get({
TableName: groupsTable,
Key: {
id: groupId
}
})
.promise()
console.log('Get group: ', result)
return !!result.Item
}
async function createImage(groupId: string, imageId: string, event: any) {
const timestamp = new Date().toISOString()
const newImage = JSON.parse(event.body)
const newItem = {
groupId,
timestamp,
imageId,
...newImage,
imageUrl: `https://${bucketName}.s3.amazonaws.com/${imageId}`
}
console.log('Storing new item: ', newItem)
await docClient
.put({
TableName: imagesTable,
Item: newItem
})
.promise()
return newItem
}
function getUploadUrl(imageId: string) {
return s3.getSignedUrl('putObject', {
Bucket: bucketName,
Key: imageId,
Expires: parseInt(urlExpiration)
})
}