-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
72 lines (59 loc) · 1.64 KB
/
app.js
File metadata and controls
72 lines (59 loc) · 1.64 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
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const controller = require('./controller');
const templating = require('./templating');
const app = new Koa();
const isProduction = process.env.NODE_ENV === 'production';
// log request URL:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
var
start = new Date().getTime(),
execTime;
await next();
execTime = new Date().getTime() - start;
ctx.response.set('X-Response-Time', `${execTime}ms`);
});
// parse user from cookie:
app.use(async (ctx, next) => {
ctx.state.user = parseUser(ctx.cookies.get('name') || '');
await next();
});
// static file support:
if (! isProduction) {
let staticFiles = require('./static-files');
app.use(staticFiles('/static/', __dirname + '/static'));
}
// parse request body:
app.use(bodyParser());
// add nunjucks as view:
app.use(templating('views', {
noCache: !isProduction,
watch: !isProduction
}));
// add controller:
app.use(controller());
app.listen(3001);
console.log('app started at port 3001...');
function parseUser(obj) {
if (!obj) {
return;
}
//console.log('try parse: ' + obj);
let s = '';
if (typeof obj === 'string') {
s = obj;
} else if (obj.headers) {
let cookies = new Cookies(obj, null);
s = cookies.get('name');
}
if (s) {
try {
let user = JSON.parse(Buffer.from(s, 'base64').toString());
//console.log(`User: ${user.mturkID}, ID: ${user.video_order}`);
return user;
} catch (e) {
// ignore
}
}
}