-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
124 lines (102 loc) · 2.6 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
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
"use strict";
const express = require("express");
const app = express();
const handler = require("./function/handler");
const bodyParser = require("body-parser");
if (process.env.RAW_BODY === "true") {
app.use(bodyParser.raw({ type: "*/*" }));
} else {
var jsonLimit = process.env.MAX_JSON_SIZE || "100kb"; //body-parser default
app.use(bodyParser.json({ limit: jsonLimit }));
app.use(bodyParser.raw()); // "Content-Type: application/octet-stream"
app.use(bodyParser.text({ type: "text/*" }));
}
app.disable("x-powered-by");
class FunctionEvent {
constructor(req) {
this.body = req.body;
this.headers = req.headers;
this.method = req.method;
this.query = req.query;
this.path = req.path;
}
}
class FunctionContext {
constructor(cb) {
this.value = 200;
this.cb = cb;
this.headerValues = {};
this.cbCalled = 0;
}
status(value) {
if (!value) {
return this.value;
}
this.value = value;
return this;
}
headers(value) {
if (!value) {
return this.headerValues;
}
this.headerValues = value;
return this;
}
succeed(value) {
let err;
this.cbCalled++;
this.cb(err, value);
}
fail(value) {
let message;
this.cbCalled++;
this.cb(value, message);
}
}
var middleware = async (req, res) => {
let cb = (err, functionResult) => {
if (err) {
console.error(err);
return res.status(500).send(err.toString ? err.toString() : err);
}
if (isArray(functionResult) || isObject(functionResult)) {
res
.set(fnContext.headers())
.status(fnContext.status())
.send(JSON.stringify(functionResult));
} else {
res
.set(fnContext.headers())
.status(fnContext.status())
.send(functionResult);
}
};
let fnEvent = new FunctionEvent(req);
let fnContext = new FunctionContext(cb);
Promise.resolve(handler(fnEvent, fnContext, cb))
.then((res) => {
if (!fnContext.cbCalled) {
fnContext.succeed(res);
}
})
.catch((e) => {
cb(e);
});
};
app.post("/*", middleware);
app.get("/*", middleware);
app.patch("/*", middleware);
app.put("/*", middleware);
app.delete("/*", middleware);
const port = process.env.http_port || 3000;
app.listen(port, () => {
console.log(`OpenFaaS Node.js listening on port: ${port}`);
});
let isArray = (a) => {
return !!a && a.constructor === Array;
};
let isObject = (a) => {
return !!a && a.constructor === Object;
};