forked from serverless/serverless-client-s3
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
265 lines (209 loc) · 8.32 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
'use strict';
module.exports = function(S) {
const path = require('path'),
SError = require(S.getServerlessPath('Error')),
SCli = require(S.getServerlessPath('utils/cli')),
BbPromise = require('bluebird'),
async = require('async'),
_ = require('lodash'),
mime = require('mime'),
fs = require('fs');
class ClientDeploy extends S.classes.Plugin {
constructor() {
super();
this.name = 'serverless-client-s3';
}
registerActions() {
S.addAction(this.clientDeploy.bind(this), {
handler: 'clientDeploy',
description: `Deploy your Serverless clients to S3 Website Bucket.`,
context: 'client',
contextAction: 'deploy',
options: [
{
option: 'stage',
shortcut: 's',
description: 'stage to populate any variables'
}, {
option: 'region',
shortcut: 'r',
description: 'region to populate any variables'
}
]
});
return BbPromise.resolve();
}
clientDeploy(evt) {
let _this = this;
_this.evt = evt;
// Flow
return _this._prompt()
.bind(_this)
.then(_this._validateAndPrepare)
.then(_this._processDeployment)
.then(function() {
_this._spinner.stop(true);
SCli.log(`Finishing deployment...`);
// display friendly message after all async operations (file uploads) are finished
process.on('exit', function (){
SCli.log(`Successfully deployed client to: ${_this.bucketName}.s3-website-${_this.evt.options.region}.amazonaws.com`);
});
return _this.evt;
});
}
_prompt() {
let _this = this;
return _this.cliPromptSelectStage('Client Deployer - Choose Stage: ', _this.evt.options.stage, true)
.then(stage => {
_this.evt.options.stage = stage;
BbPromise.resolve();
})
.then(function(){
return _this.cliPromptSelectRegion('Client Deployer - Choose Region: ', false, true, _this.evt.options.region, _this.evt.options.stage)
.then(region => {
_this.evt.options.region = region;
BbPromise.resolve();
});
});
}
_validateAndPrepare() {
let _this = this;
if (!S.utils.dirExistsSync(path.join(S.config.projectPath, 'client', 'dist'))) {
return BbPromise.reject(new SError('Could not find "client/dist" folder in your project root.'));
}
// validate stage: make sure stage exists
if (!S.getProject().validateStageExists(_this.evt.options.stage)) {
return BbPromise.reject(new SError('Stage ' + _this.evt.options.stage + ' does not exist in your project', SError.errorCodes.UNKNOWN));
}
// make sure region exists in stage
if (!S.getProject().validateRegionExists(_this.evt.options.stage, _this.evt.options.region)) {
return BbPromise.reject(new SError('Region "' + _this.evt.options.region + '" does not exist in stage "' + _this.evt.options.stage + '"'));
}
_this.project = S.getProject();
_this.aws = S.getProvider('aws');
let populatedProject = _this.project.toObjectPopulated({stage: _this.evt.options.stage, region: _this.evt.options.region});
if (!populatedProject.custom.client || !populatedProject.custom.client.bucketName) {
return BbPromise.reject(new SError('Please specify a bucket name for the client in s-project.json'));
}
_this.bucketName = populatedProject.custom.client.bucketName;
_this.clientPath = path.join(_this.project.getRootPath(), 'client', 'dist');
return BbPromise.resolve();
}
_processDeployment() {
let _this = this;
SCli.log('Deploying client to stage "' + _this.evt.options.stage + '" in region "' + _this.evt.options.region + '"...');
_this._spinner = SCli.spinner();
_this._spinner.start();
return _this.aws.request('S3', 'listBuckets', {}, _this.evt.options.stage, _this.evt.options.region)
.bind(_this)
.then(function(data) {
data.Buckets.forEach(function(bucket) {
if (bucket.Name === _this.bucketName) {
_this.bucketExists = true;
S.utils.sDebug(`Bucket ${_this.bucketName} already exists`);
}
});
})
.then(function(){
if (!_this.bucketExists) return BbPromise.resolve();
S.utils.sDebug(`Listing objects in bucket ${_this.bucketName}...`);
let params = {
Bucket: _this.bucketName
};
return _this.aws.request('S3', 'listObjects', params, _this.evt.options.stage, _this.evt.options.region)
})
.then(function(data){
if (!_this.bucketExists) return BbPromise.resolve();
S.utils.sDebug(`Deleting all objects from bucket ${_this.bucketName}...`);
if (!data.Contents[0]) {
return BbPromise.resolve();
} else {
let Objects = _.map(data.Contents, function (content) {
return _.pick(content, 'Key');
});
let params = {
Bucket: _this.bucketName,
Delete: { Objects: Objects }
};
return _this.aws.request('S3', 'deleteObjects', params, _this.evt.options.stage, _this.evt.options.region)
}})
.then(function(){
if (_this.bucketExists) return BbPromise.resolve();
S.utils.sDebug(`Creating bucket ${_this.bucketName}...`);
let params = {
Bucket: _this.bucketName
};
return _this.aws.request('S3', 'createBucket', params, _this.evt.options.stage, _this.evt.options.region)
})
.then(function(){
S.utils.sDebug(`Configuring website bucket ${_this.bucketName}...`);
let params = {
Bucket: _this.bucketName,
WebsiteConfiguration: {
IndexDocument: { Suffix: 'index.html' },
ErrorDocument: { Key: 'error.html' }
}
};
return _this.aws.request('S3', 'putBucketWebsite', params, _this.evt.options.stage, _this.evt.options.region)
})
.then(function(){
S.utils.sDebug(`Configuring policy for bucket ${_this.bucketName}...`);
let policy = {
Version: "2008-10-17",
Id: "Policy1392681112290",
Statement: [
{
Sid: "Stmt1392681101677",
Effect: "Allow",
Principal: {
AWS: "*"
},
Action: "s3:GetObject",
Resource: "arn:aws:s3:::" + _this.bucketName + '/*'
}
]
};
let params = {
Bucket: _this.bucketName,
Policy: JSON.stringify(policy)
};
return _this.aws.request('S3', 'putBucketPolicy', params, _this.evt.options.stage, _this.evt.options.region)
})
.then(function(){
return _this._uploadDirectory(_this.clientPath)
});
}
_uploadDirectory(directoryPath) {
let _this = this,
readDirectory = _.partial(fs.readdir, directoryPath);
async.waterfall([readDirectory, function (files) {
files = _.map(files, function(file) {
return path.join(directoryPath, file);
});
async.each(files, function(path) {
fs.stat(path, _.bind(function (err, stats) {
return stats.isDirectory()
? _this._uploadDirectory(path)
: _this._uploadFile(path);
}, _this));
});
}]);
}
_uploadFile(filePath) {
let _this = this,
fileKey = filePath.replace(_this.clientPath, '').substr(1).replace('\\', '/');
S.utils.sDebug(`Uploading file ${fileKey} to bucket ${_this.bucketName}...`);
fs.readFile(filePath, function(err, fileBuffer) {
let params = {
Bucket: _this.bucketName,
Key: fileKey,
Body: fileBuffer,
ContentType: mime.lookup(filePath)
};
// TODO: remove browser caching
return _this.aws.request('S3', 'putObject', params, _this.evt.options.stage, _this.evt.options.region)
});
}
}
return ClientDeploy;
};