-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
87 lines (84 loc) · 2.96 KB
/
index.js
File metadata and controls
87 lines (84 loc) · 2.96 KB
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
const { setMethodMiddlewares } = require("./methods");
const api = () => {
let middlewares = {};
let obj = {
req: {},
middleWareCount: -1,
res: {
"status": (status) => {
obj.status = status
}
},
mw: [],
use: (mwFunction) => {
if (typeof mwFunction === "function") {
++obj.middleWareCount
const key = String(obj.middleWareCount)
middlewares[key] = {}
middlewares[key]["function"] = mwFunction
middlewares[key]["order"] = String(obj.middleWareCount)
middlewares[key]["description"] = "anonymous"
if(mwFunction.length === 4) {
middlewares[key]["errorHandler"] = true
}
}
},
handle: (event, context, callback) => {
obj.nextCounter = -1
obj.mw = Object.keys(middlewares)
obj.status = 200
obj.req = {
"body": event.body,
"method": event.httpMethod,
"path": event.path,
"query": event.queryStringParameters
}
obj.res = {
"json": (body) => {
const response = {
statusCode: obj.status || 200,
body: JSON.stringify(body),
multiValueHeaders: obj.res.headers
}
context.done(null, response)
},
"headers": {}
}
obj.res.status = (status) => {
obj["status"] = status
}
obj.res.send = (status) => {
context.done(null, {
statusCode: obj.status || 200,
multiValueHeaders: obj.res.headers
})
}
obj.res.setHeaders = (key, value) => {
obj.res.headers[key] = typeof value === "string" ? [value] : value
}
obj.next(obj.nextCounter)
},
next: async () => {
++obj.nextCounter
try {
if (middlewares[obj.nextCounter].function) {
await middlewares[obj.nextCounter].function(obj.req, obj.res, obj.next)
} else {
return
}
} catch(err){
++obj.nextCounter
while(middlewares[obj.nextCounter] && middlewares[obj.nextCounter].function && !middlewares[obj.nextCounter]["errorHandler"]) {
++obj.nextCounter
}
if(middlewares[obj.nextCounter] && middlewares[obj.nextCounter].function) {
middlewares[obj.nextCounter].function(err, obj.req, obj.res, obj.next)
}
}
},
middlewares
};
setMethodMiddlewares(obj)
return obj
};
exports.api = api;