forked from funkybob/serverless-s3-deploy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (92 loc) · 2.68 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
103
104
105
106
107
108
109
110
111
112
'use strict';
const glob = require('glob-all');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const globOpts = {
nodir: true
};
class Assets {
constructor (serverless, options) {
this.serverless = serverless;
this.options = options;
this.provider = this.serverless.getProvider('aws');
let config = this.serverless.service.custom.assets;
if(Array.isArray(config)) {
config = {targets: config};
}
this.config = Object.assign({}, {
auto: false,
targets: [],
}, config);
this.commands = {
s3deploy: {
usage: 'Deploy assets to S3 bucket',
lifecycleEvents: [
'deploy'
],
options: {
verbose: {
usage: 'Increase verbosity',
shortcut: 'v'
},
bucket: {
usage: 'Limit the deploy to a specific bucket',
shortcut: 'b'
}
}
}
};
this.hooks = {
's3deploy:deploy': () => Promise.resolve().then(this.deployS3.bind(this)),
'after:deploy:finalize': () => Promise.resolve().then(this.afterDeploy.bind(this))
};
}
/*
* Handy method for logging (when `verbose` is set)
*/
log(message) {
if(this.options.verbose) {
this.serverless.cli.log(message);
}
}
afterDeploy() {
if(this.config.auto) {
this.deployS3();
}
}
deployS3() {
let assetSets = this.config.targets;
// glob
return new Promise(resolve => {
assetSets.forEach(assets => {
const bucket = assets.bucket;
const prefix = assets.prefix || '';
assets.files.forEach(opt => {
this.log(`Bucket: ${bucket}:${prefix}`);
if(this.options.bucket && this.options.bucket !== bucket) {
this.log('Skipping');
return;
}
this.log(`Path: ${opt.source}`);
const cfg = Object.assign({}, globOpts, {cwd: opt.source});
glob.sync(opt.globs, cfg).forEach(filename => {
const body = fs.readFileSync(path.join(opt.source, filename));
const type = mime.lookup(filename) || opt.defaultContentType || 'application/octet-stream';
this.log(`\tFile: ${filename} (${type})`);
const details = Object.assign({
ACL: assets.acl || 'public-read',
Body: body,
Bucket: bucket,
Key: path.join(prefix, filename),
ContentType: type
}, opt.headers || {});
this.provider.request('S3', 'putObject', details, this.options.stage, this.options.region);
});
});
});
resolve();
});
}
}
module.exports = Assets;