-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
305 lines (239 loc) · 9.64 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
'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'),
https = require('https'),
indexHtmlUrl = 'https://raw.githubusercontent.com/graphql/graphiql/d5f027ae851d357c6d83e6b908baba888b5b7282/example/index.html';
class ClientDeploy extends S.classes.Plugin {
constructor() {
super();
this.name = 'serverless-graphiql'; // Define your plugin's name
}
registerActions() {
S.addAction(this.clientDeploy.bind(this), {
handler: 'clientDeploy',
description: `Deploy a GraphiQL web client to a public S3 Website Bucket.`,
context: 'graphiql',
contextAction: 'deploy',
options: [
{
option: 'stage',
shortcut: 's',
description: 'Optional - JS file to run as custom initialization code'
}, {
option: 'region',
shortcut: 'r',
description: 'Optional - add URL prefix to each lambda'
}
]
});
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('GraphiQL Deployer - Choose Stage: ', _this.evt.options.stage, true)
.then(stage => {
_this.evt.options.stage = stage;
BbPromise.resolve();
})
.then(function(){
return _this.cliPromptSelectRegion('GraphiQL Deployer - Choose Region: ', true, 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, 'plugins', 'serverless-graphiql', 'node_modules', 'graphiql'))) {
return BbPromise.reject(new SError('Could not find "node_modules/graphiql" 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');
_this.projectBucketRegion = S.getProject().getVariables().projectBucketRegion;
_this.bucketName = `${_this.project.getName()}.graphiql.${_this.evt.options.stage}.${_this.evt.options.region}`;
_this.clientPath = path.join(_this.project.getRootPath(), 'plugins', 'serverless-graphiql', 'node_modules', 'graphiql');
return BbPromise.resolve();
}
_processDeployment() {
let _this = this;
SCli.log('Deploying GraphiQL 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.projectBucketRegion)
.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.projectBucketRegion)
})
.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.projectBucketRegion)
}})
.then(function(){
if (!_this.bucketExists) return BbPromise.resolve();
S.utils.sDebug(`Deleting bucket ${_this.bucketName}...`);
let params = {
Bucket: _this.bucketName
};
return _this.aws.request('S3', 'deleteBucket', params, _this.evt.options.stage, _this.projectBucketRegion)
})
.then(function(){
S.utils.sDebug(`Creating bucket ${_this.bucketName}...`);
let params = {
Bucket: _this.bucketName
};
return _this.aws.request('S3', 'createBucket', params, _this.evt.options.stage, _this.projectBucketRegion)
})
.then(function(){
S.utils.sDebug(`Configuring website bucket ${_this.bucketName}...`);
let params = {
Bucket: _this.bucketName,
WebsiteConfiguration: {
IndexDocument: { Suffix: 'index.html' }
}
};
return _this.aws.request('S3', 'putBucketWebsite', params, _this.evt.options.stage, _this.projectBucketRegion)
})
.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.projectBucketRegion)
})
.then(function(){
return _this._downloadIndexHtml()
})
.then(function(){
return _this._uploadDirectory(_this.clientPath)
});
}
_downloadIndexHtml(){ //Since GraphiQL's example isn't included after `npm install`, fetch from GitHub
let _this = this;
//Skip if already downloaded
let htmlPath = path.join(_this.project.getRootPath(), 'plugins', 'serverless-graphiql', 'node_modules', 'graphiql', 'index.html');
if(fs.existsSync(htmlPath)) return BbPromise.resolve()
SCli.log("Using htmlPath: " + htmlPath);
//Fetch file
return BbPromise.fromCallback(function(callback){
https.get(indexHtmlUrl, function(response) {
var body = '';
response.on('error', callback);
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
SCli.log('writing HTML: ', body);
fs.writeFileSync(htmlPath, body);
callback(null);
});
});
});
}
_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);
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.projectBucketRegion)
});
}
}
return ClientDeploy;
};