-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
102 lines (90 loc) · 2.6 KB
/
index.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
const { execFile } = require('child_process');
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
const path = require('path');
const mime = require('mime-types');
const cfnCR = require('cfn-custom-resource');
const AWS = require('aws-sdk');
var glob = require('glob');
const s3 = new AWS.S3();
exports.handler = async message => {
console.log(message);
try {
const tmpDir = `/tmp/react-front-end${process.pid}`;
const npm = 'npm';
await spawnPromise('rm', ['-rf', tmpDir]);
await spawnPromise('cp', ['-R', 'front-end/', tmpDir]);
await spawnPromise(
npm,
['--production',
'--no-progress',
'--loglevel=error',
'--cache', path.join('/tmp', 'npm'),
'--userconfig', path.join('/tmp', 'npmrc'),
'install'
],
{cwd: tmpDir}
);
await spawnPromise(
npm,
['--production',
'--no-progress',
'--loglevel=error',
'--cache', path.join('/tmp', 'npm'),
'--userconfig', path.join('/tmp', 'npmrc'),
'run', 'build'
],
{cwd: tmpDir}
);
const builtPaths = glob.sync(`${tmpDir}/build/**/*`);
console.log(builtPaths);
builtPaths.forEach(async (path) => {
if (!fs.lstatSync(path).isFile()) {
return;
}
const mimeType = mime.lookup(path) || 'application/octet-stream';
console.log(mimeType);
const fileHandle = await readFile(path);
const key = path.replace(`${tmpDir}/build/`, '');
const params = {
ACL: 'public-read',
ContentType: mimeType,
Body: fileHandle,
Bucket: process.env.BUCKET_NAME,
Key: key
};
console.log(params);
const s3Response = await s3.putObject(params).promise();
console.log(s3Response);
});
} catch (error) {
console.log(error);
await cfnCR.sendFailure(error.message, message);
} finally {
await cfnCR.sendSuccess('deployFrontEnd', {}, message);
}
};
function spawnPromise (command, args, options) {
console.log(`Running \`${command} '${args.join("' '")}'\`...`);
options = options || {};
if (!options.env) {
options.env = {};
}
Object.assign(options.env, process.env);
return new Promise((resolve, reject) => {
execFile(command, args, options, (err, stdout, stderr) => {
console.log('STDOUT:');
console.log(stdout);
console.log('STDERR:');
console.log(stderr);
if (err) {
err.stdout = stdout;
err.stderr = stderr;
reject(err);
} else {
resolve({stdout: stdout, stderr: stderr});
}
});
});
}