-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththenContext.js
More file actions
67 lines (54 loc) · 2.04 KB
/
thenContext.js
File metadata and controls
67 lines (54 loc) · 2.04 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
/*global module, require*/
module.exports = (function() {
"use strict";
ThenContext.prototype.promisify = returnSelfAsResolvedPromise;
return ThenContext;
function ThenContext(event, ctx, cb) {
let thenCtx = this;
thenCtx.event = event;
thenCtx.ctx = ctx;
thenCtx.cb = cb;
thenCtx.config = undefined;
thenCtx.res = {};
thenCtx.finalize = function() { logAndCallCb.apply(thenCtx, arguments) };
return thenCtx;
}
function returnSelfAsResolvedPromise() {
let self = this instanceof ThenContext ? this : new ThenContext(arguments);
return Promise.resolve(self);
}
function logAndCallCb(ctxOrErr) {
let myCtx = this;
let isError = ctxOrErr && (ctxOrErr !== myCtx);
let err = isError ? ctxOrErr : undefined;
let res = castResponse(err, myCtx);
log(err, myCtx);
return myCtx.cb(null, res);
function castResponse(err, myCtx) {
let res = myCtx.res, contentType;
if (err) {
res.body = err.message;
} else if (!res.body) {
contentType = 'application/json';
res.body = res.json ? JSON.stringify(res.json) : '{"result":"Ok"}';
}
if (!res.headers) res.headers = {};
res.headers['Content-Type'] = contentType ? contentType : 'text/plain';
if (!res.statusCode)
res.statusCode = err ? '400' : '200';
return res;
}
function log(err, myCtx) {
if (err)
console.log("Error: ", err);
if ( process.env.debug >= 1 ) {
console.log("Event: ", JSON.stringify(myCtx.event));
console.log("Response: ", JSON.stringify(myCtx.res));
}
if ( process.env.debug >= 2 )
console.log("Context: ", JSON.stringify(myCtx.ctx));
if ( process.env.debug >= 3 )
console.log("Env: ", JSON.stringify(process.env));
}
}
})();