-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheko-koa.js
197 lines (174 loc) · 4.73 KB
/
eko-koa.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
const Koa = require("koa");
const render = require("koa-ejs");
const logger = require("koa-logger");
const Router = require("koa-router");
const etag = require("koa-etag");
const conditional = require("koa-conditional-get");
const helmet = require("koa-helmet");
const compress = require("koa-compress");
const bodyParser = require("koa-bodyparser");
const session = require("koa-session");
const flash = require("koa-flash-simple");
const locale = require("koa-locale");
const i18n = require("koa-i18n");
const path = require("path");
const cron = require("cron");
const Youch = require("youch");
const PrettyError = require("pretty-error");
PrettyError.start();
const objection = require("objection");
const knexDependency = require("knex");
const router = new Router();
const pe = new PrettyError();
const app = new Koa();
let config;
const isDevelop =
!process.env.NODE_ENV || process.env.NODE_ENV === "development";
if (isDevelop) {
config = require(`./config/development`);
} else {
config = require(`./config/${process.env.NODE_ENV}`);
}
app.keys = config.koa.keys;
const renderConfig = Object.assign(
{},
{
root: path.join(__dirname, "view"),
layout: "template",
viewExt: "ejs",
cache: !isDevelop,
debug: false
},
config.ejs
);
const sessionConfig = Object.assign(
{},
{
key: "koa:sess" /** (string) cookie key (default is koa:sess) */,
maxAge: 86400000,
overwrite: true /** (boolean) can overwrite or not (default true) */,
httpOnly: true /** (boolean) httpOnly or not (default true) */,
signed: true /** (boolean) signed or not (default true) */,
rolling: false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */,
renew: false /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
},
config.session
);
const i18nConfig = Object.assign(
{},
{
directory: "./locales",
extension: ".json",
locales: ["en", "ru"], // `zh-CN` defualtLocale, must match the locales to the filenames
modes: [
"query", // optional detect querystring - `/?locale=en-US`
"subdomain", // optional detect subdomain - `zh-CN.koajs.com`
"cookie", // optional detect cookie - `Cookie: locale=zh-TW`
"header", // optional detect header - `Accept-Language: zh-CN,zh;q=0.5`
"url", // optional detect url - `/en`
"tld" // optional detect tld(the last domain) - `koajs. // optional custom function (will be bound to the koa context)
]
},
config.i18n
);
const knex = knexDependency(
Object.assign(
{},
{
client: "sqlite3",
debug: true,
connection: {
filename: "./mydb.sqlite"
}
},
config.knex
)
);
const globalSessionHandler = async (ctx, next) => {
if (ctx.path === "/favicon.ico") return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
await next();
};
const errorPageHandler = async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = 500;
console.log(pe.render(err));
if (isDevelop) {
ctx.body = await new Youch(err, ctx.request).toHTML();
}
}
};
const notFoundPageHandler = async (ctx, next) => {
if (ctx.status == 404) {
await _renderWithHelpers(ctx, "404", { user: "Not found" });
}
};
_renderWithHelpers = (ctx, view, data) => {
return ctx.render(
view,
Object.assign(
{},
{
flash: ctx.flash.get(),
__: (...arg) => ctx.i18n.__(arg),
currentLang: ctx.cookies.get("locale")
},
data
)
);
};
class Model extends objection.Model {
$beforeInsert() {
this.created_at = new Date();
}
$beforeUpdate() {
this.updated_at = new Date();
}
}
class Controller {
async render(ctx, view, data) {
return await _renderWithHelpers(ctx, view, data);
}
changeLang(ctx, lang) {
ctx.cookies.set("locale", ctx.params.language);
}
async json(ctx, data) {
ctx.body = data;
}
}
objection.Model.knex(knex);
locale(app);
render(app, renderConfig);
app
.use(logger())
.use(helmet())
.use(conditional())
.use(compress())
.use(etag())
.use(bodyParser())
.use(session(sessionConfig, app))
.use(i18n(app, i18nConfig))
.use(globalSessionHandler)
.use(flash())
.use(errorPageHandler)
.use(router.routes())
.use(router.allowedMethods())
.use(require("koa-static")(__dirname + "/public"))
.use(notFoundPageHandler);
const port = config.koa.port || 3000;
app.listen(port);
console.log("Listening on port " + port);
require("./jobs/cronjobs");
module.exports = {
app,
router,
knex,
objection,
cron,
CronJob: cron.CronJob,
Model,
Controller
};