-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
62 lines (44 loc) · 1.8 KB
/
index.mjs
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';
import Sharp from 'sharp';
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
const s3 = new S3Client();
const BUCKET = '<BUCKET NAME>';
export const handler = async (event) => {
const response = event.Records[0].cf.response;
if (response.status === '404') {
const request = event.Records[0].cf.request;
if (request.uri.startsWith('/generated/') === false) {
return response;
}
const path = request.uri;
const parts = path.substring(1).split('/');
const filename = parts.pop();
const format = filename.split('.').pop();
const prefix = parts.shift();
const [ width, height ] = parts.shift().split('x');
const originalKey = parts.filter(value => value.trim().length > 0).concat(filename).join('/');
const getObjectCommand = new GetObjectCommand({
Bucket: BUCKET,
Key: originalKey,
});
const s3Response = await s3.send(getObjectCommand);
const body = await s3Response.Body.transformToByteArray();
const buffer = await Sharp(body).resize(parseInt(width), parseInt(height), { fit: Sharp.fit.inside }).toBuffer();
const putObjectCommand = new PutObjectCommand({
Bucket: BUCKET,
Key: path.substring(1),
Body: buffer,
ContentType: 'image/' + (format === 'jpg' ? 'jpeg' : format),
CacheControl: 'max-age=31536000',
Tagging: (new URLSearchParams({ type: 'thumbnail', source: 'Lambda' })).toString(),
});
await s3.send(putObjectCommand);
response.status = 200;
response.body = buffer.toString('base64');
response.bodyEncoding = 'base64';
response.headers['content-type'] = [{ key: 'Content-Type', value: 'image/' + (format === 'jpg' ? 'jpeg' : format) }];
response.ContentLength = buffer.length;
return response;
}
return response;
};