-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
82 lines (69 loc) · 1.85 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
'use strict';
const BbPromise = require('bluebird');
class BodyOption {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
invoke: {
lifecycleEvents: [
"invoke",
],
options: {
body: {
usage: 'The HTTP body data in the event, format: Json string or json file path.',
shortcut: 'b',
},
},
commands: {
local: {
lifecycleEvents: [
"invoke",
],
options: {
body: {
usage: 'The HTTP body data in the event, format: Json string or json file path.',
shortcut: 'b',
},
},
},
},
},
};
this.hooks = {
'before:invoke:local:invoke': this.handleBodyOption.bind(this),
'before:invoke:invoke': this.handleBodyOption.bind(this),
}
}
handleBodyOption() {
if (this.options.body !== undefined) {
const bodyOption = this.options.body;
const bodyJson = (this.isFilePath(bodyOption))
? this.getBodyFromPath(bodyOption)
: this.getDataFromCLI(bodyOption);
this.wrapBodyToEvent(bodyJson);
return BbPromise.resolve(this);
}
}
wrapBodyToEvent(body) {
this.options.data = {'body': JSON.stringify(body).trim() };
}
isFilePath(arg) {
return this.serverless.utils.fileExistsSync(arg);
}
getBodyFromPath(path) {
this.serverless.cli.log(`Getting body data from path: ${path}`);
return this.serverless.utils.readFileSync(path);
}
getDataFromCLI(body) {
this.serverless.cli.log(`Getting body data from stdin: ${body}`);
let data;
try {
data = JSON.parse(body);
} catch(e) {
data = "(" + body + ")";
}
return data;
}
}
module.exports = BodyOption;