-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
63 lines (60 loc) · 1.64 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
import express from 'express';
import { reqLogger } from './lib/logger.js';
import { handleUpdateRequest, update } from './lib/update.js';
import { generateHomepage } from './lib/utils.js';
import parser from './lib/parser.js';
import hitokoto from './api/hitokoto.js';
import media from './api/media.js';
function startSever(config, logger, resources) {
const app = express();
config.api.list.forEach((api) => {
switch (api.type) {
case 'media':
app.use(
api.path,
express.json(),
express.urlencoded({ extended: true }),
parser,
media.bind(null, { config, logger, resources }),
);
break;
case 'hitokoto':
app.use(
api.path,
express.json(),
express.urlencoded({ extended: true }),
parser,
hitokoto.bind(null, { config, logger, resources }),
);
break;
default:
throw new Error(`Invalid API type:${api.type}!`);
}
});
if (config.update.type === 'timing') {
setInterval(update, config.update.frequency * 1000, {
config,
logger,
resources,
});
} else {
app.use(
'/update',
express.raw({
limit: '10mb',
type: ['application/json', 'application/x-www-form-urlencoded'],
}),
handleUpdateRequest.bind(null, { config, logger }),
);
}
// log request
app.use('/', ...reqLogger(logger));
// homepage
app.use('^/$', generateHomepage);
const { host, port } = config;
// start server
app.listen(port, host, () => {
logger.info(`Start listening on http://${host}:${port}`);
});
}
export default startSever;