This repository was archived by the owner on Sep 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathinvoke.js
276 lines (255 loc) · 8.29 KB
/
invoke.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
const chalk = require("chalk");
const Command = require("@netlify/cli-utils");
const { flags } = require("@oclif/command");
const inquirer = require("inquirer");
const { serverSettings } = require("../../detect-server");
const fetch = require("node-fetch");
const fs = require("fs");
const path = require("path");
const { getFunctions } = require("../../utils/get-functions");
// https://www.netlify.com/docs/functions/#event-triggered-functions
const eventTriggeredFunctions = [
"deploy-building",
"deploy-succeeded",
"deploy-failed",
"deploy-locked",
"deploy-unlocked",
"split-test-activated",
"split-test-deactivated",
"split-test-modified",
"submission-created",
"identity-validate",
"identity-signup",
"identity-login"
];
class FunctionsInvokeCommand extends Command {
async run() {
let { flags, args } = this.parse(FunctionsInvokeCommand);
const { api, site, config } = this.netlify;
const functionsDir =
flags.functions ||
(config.dev && config.dev.functions) ||
(config.build && config.build.functions);
if (typeof functionsDir === "undefined") {
this.error(
"functions directory is undefined, did you forget to set it in netlify.toml?"
);
process.exit(1);
}
let settings = await serverSettings(Object.assign({}, config.dev, flags));
if (!(settings && settings.command)) {
settings = {
noCmd: true,
port: 8888,
proxyPort: 3999,
dist
};
}
const functions = getFunctions(functionsDir);
const functionToTrigger = await getNameFromArgs(functions, args, flags);
let headers = {};
let body = {};
if (eventTriggeredFunctions.includes(functionToTrigger)) {
/** handle event triggered fns */
// https://www.netlify.com/docs/functions/#event-triggered-functions
const parts = functionToTrigger.split("-");
if (parts[0] === "identity") {
// https://www.netlify.com/docs/functions/#identity-event-functions
body.event = parts[1];
body.user = {
email: "[email protected]",
user_metadata: {
TODO: "mock our netlify identity user data better"
}
};
} else {
// non identity functions seem to have a different shape
// https://www.netlify.com/docs/functions/#event-function-payloads
body.payload = {
TODO: "mock up payload data better"
};
body.site = {
TODO: "mock up site data better"
};
}
} else {
// NOT an event triggered function, but may still want to simulate authentication locally
let _isAuthed = false;
if (typeof flags.auth === "undefined") {
const { isAuthed } = await inquirer.prompt([
{
type: "confirm",
name: "isAuthed",
message: `Invoke with emulated Netlify Identity authentication headers? (pass -auth/--no-auth to override)`,
default: true
}
]);
_isAuthed = isAuthed;
} else {
_isAuthed = flags.auth;
}
if (_isAuthed) {
headers = {
authorization:
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb3VyY2UiOiJuZXRsaWZ5IGZ1bmN0aW9uczp0cmlnZ2VyIiwidGVzdERhdGEiOiJORVRMSUZZX0RFVl9MT0NBTExZX0VNVUxBVEVEX0pXVCJ9.Xb6vOFrfLUZmyUkXBbCvU4bM7q8tPilF0F03Wupap_c"
};
// you can decode this https://jwt.io/
// {
// "source": "netlify functions:trigger",
// "testData": "NETLIFY_DEV_LOCALLY_EMULATED_JWT"
// }
}
}
const payload = processPayloadFromFlag(flags.payload);
body = Object.assign({}, body, payload);
// fetch
fetch(
`http://localhost:${
settings.port
}/.netlify/functions/${functionToTrigger}` +
formatQstring(flags.querystring),
{
method: "post",
headers,
body: JSON.stringify(body)
}
)
.then(response => {
let data;
data = response.text();
try {
// data = response.json();
data = JSON.parse(data);
} catch (err) {}
return data;
})
.then(console.log)
.catch(err => {
console.error("ran into an error invoking your function");
console.error(err);
});
}
}
function formatQstring(querystring) {
if (querystring) {
return "?" + querystring;
} else {
return "";
}
}
/** process payloads from flag */
function processPayloadFromFlag(payloadString) {
if (payloadString) {
// case 1: jsonstring
let payload = tryParseJSON(payloadString);
if (!!payload) return payload;
// case 2: jsonpath
const payloadpath = path.join(process.cwd(), payloadString);
const pathexists = fs.existsSync(payloadpath);
if (!payload && pathexists) {
try {
payload = require(payloadpath); // there is code execution potential here
return payload;
} catch (err) {
console.error(err);
payload = false;
}
}
// case 3: invalid string, invalid path
return false;
}
}
// prompt for a name if name not supplied
// also used in functions:create
async function getNameFromArgs(functions, args, flags) {
// let functionToTrigger = flags.name;
// const isValidFn = Object.keys(functions).includes(functionToTrigger);
if (flags.name && args.name) {
console.error(
"function name specified in both flag and arg format, pick one"
);
process.exit(1);
}
let functionToTrigger;
if (flags.name && !args.name) functionToTrigger = flags.name;
// use flag if exists
else if (!flags.name && args.name) functionToTrigger = args.name;
const isValidFn = Object.keys(functions).includes(functionToTrigger);
if (!functionToTrigger || !isValidFn) {
if (!isValidFn) {
this.warn(
`Function name ${chalk.yellow(
functionToTrigger
)} supplied but no matching function found in your functions folder, forcing you to pick a valid one...`
);
}
const { trigger } = await inquirer.prompt([
{
type: "list",
message: "Pick a function to trigger",
name: "trigger",
choices: Object.keys(functions)
}
]);
functionToTrigger = trigger;
}
return functionToTrigger;
}
FunctionsInvokeCommand.description = `trigger a function while in netlify dev with simulated data, good for testing function calls including Netlify's Event Triggered Functions`;
FunctionsInvokeCommand.aliases = ["function:trigger"];
FunctionsInvokeCommand.examples = [
"$ netlify functions:invoke",
"$ netlify functions:invoke myfunction",
"$ netlify functions:invoke --name myfunction",
"$ netlify functions:invoke --name myfunction --auth",
"$ netlify functions:invoke --name myfunction --no-auth",
'$ netlify functions:invoke myfunction --payload "{"foo": 1}"',
'$ netlify functions:invoke myfunction --querystring "foo=1',
'$ netlify functions:invoke myfunction --payload "./pathTo.json"'
];
FunctionsInvokeCommand.args = [
{
name: "name",
description: "function name to invoke"
}
];
FunctionsInvokeCommand.flags = {
name: flags.string({
char: "n",
description: "function name to invoke"
}),
functions: flags.string({
char: "f",
description: "Specify a functions folder to parse, overriding netlify.toml"
}),
querystring: flags.string({
char: "q",
description: "Querystring to add to your function invocation"
}),
payload: flags.string({
char: "p",
description:
"Supply POST payload in stringified json, or a path to a json file"
}),
auth: flags.boolean({
char: "a",
description:
"simulate Netlify Identity authentication JWT. pass --no-auth to affirm unauthenticated request",
allowNo: true
})
};
module.exports = FunctionsInvokeCommand;
// https://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try
function tryParseJSON(jsonString) {
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
} catch (e) {}
return false;
}