This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
serve.js
187 lines (166 loc) · 4.88 KB
/
serve.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
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const expressLogging = require("express-logging");
const queryString = require("querystring");
const path = require("path");
const getPort = require("get-port");
const chokidar = require("chokidar");
const { findModuleDir, findHandler } = require("./finders");
const defaultPort = 30001;
function handleErr(err, response) {
response.statusCode = 500;
response.write("Function invocation failed: " + err.toString());
response.end();
console.log("Error during invocation: ", err);
return;
}
function createCallback(response) {
return function callback(err, lambdaResponse) {
if (err) {
return handleErr(err, response);
}
response.statusCode = lambdaResponse.statusCode;
for (const key in lambdaResponse.headers) {
response.setHeader(key, lambdaResponse.headers[key]);
}
response.write(
lambdaResponse.isBase64Encoded
? Buffer.from(lambdaResponse.body, "base64")
: lambdaResponse.body
);
response.end();
};
}
function promiseCallback(promise, callback) {
if (!promise) return;
if (typeof promise.then !== "function") return;
if (typeof callback !== "function") return;
promise.then(
function(data) {
callback(null, data);
},
function(err) {
callback(err, null);
}
);
}
function getHandlerPath(functionPath) {
if (functionPath.match(/\.js$/)) {
return functionPath;
}
return path.join(functionPath, `${path.basename(functionPath)}.js`);
}
function createHandler(dir, options) {
const functions = {};
fs.readdirSync(dir).forEach(file => {
if (dir === "node_modules") {
return;
}
const functionPath = path.resolve(path.join(dir, file));
const handlerPath = findHandler(functionPath);
if (!handlerPath) {
return;
}
if (path.extname(functionPath) === ".js") {
functions[file.replace(/\.js$/, "")] = {
functionPath,
moduleDir: findModuleDir(functionPath)
};
} else if (fs.lstatSync(functionPath).isDirectory()) {
functions[file] = {
functionPath: handlerPath,
moduleDir: findModuleDir(functionPath)
};
}
});
Object.keys(functions).forEach(name => {
const fn = functions[name];
const clearCache = () => {
const before = module.paths;
module.paths = [fn.moduleDir];
delete require.cache[require.resolve(fn.functionPath)];
module.paths = before;
};
fn.watcher = chokidar.watch(
[fn.functionPath, path.join(fn.moduleDir, "package.json")],
{
ignored: /node_modules/
}
);
fn.watcher
.on("add", clearCache)
.on("change", clearCache)
.on("unlink", clearCache);
});
return function(request, response) {
// handle proxies without path re-writes (http-servr)
const cleanPath = request.path.replace(/^\/.netlify\/functions/, "");
const func = cleanPath.split("/").filter(function(e) {
return e;
})[0];
if (!functions[func]) {
response.statusCode = 404;
response.end("Function not found...");
return;
}
const { functionPath, moduleDir } = functions[func];
let handler;
let before = module.paths;
try {
module.paths = [moduleDir];
handler = require(functionPath);
module.paths = before;
} catch (err) {
module.paths = before;
handleErr(err, response);
return;
}
const isBase64 =
request.body &&
!(request.headers["content-type"] || "").match(
/text|application|multipart\/form-data/
);
const lambdaRequest = {
path: request.path,
httpMethod: request.method,
queryStringParameters: queryString.parse(request.url.split(/\?(.+)/)[1]),
headers: request.headers,
body: isBase64
? Buffer.from(request.body.toString(), "utf8").toString("base64")
: request.body,
isBase64Encoded: isBase64
};
const callback = createCallback(response);
const promise = handler.handler(lambdaRequest, {}, callback);
promiseCallback(promise, callback);
};
}
async function serveFunctions(settings, options) {
options = options || {};
const app = express();
const dir = settings.functionsDir;
const port = await getPort({ port: settings.port || defaultPort });
app.use(bodyParser.raw({ limit: "6mb" }));
app.use(bodyParser.text({ limit: "6mb", type: "*/*" }));
app.use(
expressLogging(console, {
blacklist: ["/favicon.ico"]
})
);
app.get("/favicon.ico", function(req, res) {
res.status(204).end();
});
app.all("*", createHandler(dir, options));
app.listen(port, function(err) {
if (err) {
console.error("Unable to start lambda server: ", err);
process.exit(1);
}
console.log(`Lambda server is listening on ${port}`);
});
return Promise.resolve({
port
});
}
module.exports = { serveFunctions };