-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
68 lines (57 loc) · 2.15 KB
/
handler.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
'use strict';
const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const path = require('path');
const s3 = new AWS.S3();
module.exports.hello = (event, context, callback) => {
const BUCKET = process.env.BUCKET;
const STAGE = process.env.STAGE;
const params = {
Bucket: BUCKET,
Key: path.join(STAGE, 'breadcrumb.txt'),
};
//fetch breadcrumb.txt to find live SHA for environment
s3.getObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
const liveSha = data.Body.toString().trim();
console.log('live sha for '+STAGE+' is '+liveSha);
params.Key = path.join(STAGE, liveSha, 'prefix-index.html');
//fetch prefix html to get <head> code
s3.getObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
const prefix = data.Body.toString().trim();
let content = prefix;
//add tokens to <head>
content += '<script>window.token=\'' + process.env.TOKEN + '\';window.globalToken=\''+ process.env.GLOBAL_VAR+'\';</script>';
//get postfix html (post <head>)
params.Key = path.join(STAGE, liveSha, 'postfix-index.html');
s3.getObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
const postfix = data.Body.toString().trim();
content += postfix;
//replace stage placeholder
content = content.replace(/<%REPLACE_WITH_STAGE%>/g, STAGE);
//replace sha placeholder with liveSha
content = content.replace(/<%REPLACE_WITH_SHA%>/g, liveSha);
const response = {
statusCode: 200,
headers: {
'Content-type': 'text/html',
},
body: content,
};
callback(null, response);
}
})
}
});
}
});
// Use this code if you don't use the http event with the LAMBDA-PROXY integration
// callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};