-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (76 loc) · 2.35 KB
/
app.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
const Koa = require('koa');
const logger = require('koa-logger');
const koaBody = require('koa-body');
const views = require('koa-views');
const staticCache = require('koa-static-cache');
const bodyparser = require('koa-bodyparser');
const nunjucks = require('nunjucks');
const moment = require('moment');
const path = require('path');
const p = require('./package.json');
const config = require('./config')
const app = global.app = module.exports = new Koa();
// view setting
const viewPath = path.join(__dirname, config.viewPath);
const engineEnv = nunjucks.configure('views', {
autoescape: false,
});
engineEnv.addFilter('time', function(input, format) {
if (!input) {
return "";
}
return moment(input).format(format || "YYYY-MM-DD HH:mm:ss");
});
engineEnv.addFilter('env', function(input, singnal) {
if (!input) {
return config[singnal];
}
return input;
});
engineEnv.addGlobal('rootPath', config.rootPath);
engineEnv.addGlobal('cdnPath', config.cdnPath);
const getAssetRoot = () => {
if (config.cdnEnable && config.cdnPath) {
let rootCdnPath = config.cdnPath + '/' + p.name + '/' + p.version;
if (config.cdnPathPrefix) {
rootCdnPath = '/' + config.cdnPathPrefix;
}
return rootCdnPath
} else {
return config.rootPath;
}
}
//get single file path, like server for img
engineEnv.addGlobal("asset", function(url) {
return getAssetRoot() + url;
})
engineEnv.addGlobal('style', function() {
let urls = Array.prototype.slice.call(arguments);
let result = [];
urls.forEach(function(url) {
url = getAssetRoot() + url;
result.push(`<link rel="stylesheet" href="${url}"></link>`);
});
return new nunjucks.runtime.SafeString(result.join('\n'))
});
engineEnv.addGlobal('script', function() {
let urls = Array.prototype.slice.call(arguments)
let result = [];
urls.forEach(function(url) {
let scriptPath = getAssetRoot() + url;
result.push(`<script src="${scriptPath}"></script>`)
});
return result.join('\n');
})
app.use(views(viewPath, {map: { html: 'nunjucks' }}));
app.use(bodyparser());
app.use(logger());
app.use(koaBody());
app.use(require('koa-static')(__dirname + `/${config.static}`));
// app.use(staticCache(config.static));
// router
require('./routes')(app);
if (!!module.parent) app.callback();
app.listen(config.port, () => {
console.log('koa app was launched at port:', config.port)
});