-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhitokoto.js
More file actions
62 lines (57 loc) · 1.57 KB
/
hitokoto.js
File metadata and controls
62 lines (57 loc) · 1.57 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
import iconv from 'iconv-lite';
import { isCategoryInclude } from '../lib/utils.js';
const hitokoto = ({ resources }, req, res, next) => {
const {
category = 'all',
format = 'json',
encoding = 'utf-8',
seletor = '#hitokoto',
} = req.parsedParams;
// Check encoding
if (!iconv.encodingExists(encoding)) {
res.status(400);
next(`Unsupported encoding: ${encoding}`);
}
// Selete a random hitokoto
const hitokotos = [];
Object.entries(resources[req.baseUrl]).forEach(([c, h]) => {
if (isCategoryInclude(c, category)) {
hitokotos.push(...h.map((obj) => ({ ...obj, category: c })));
}
});
if (hitokotos.length === 0) {
res.status(500);
next('No matching hitokoto found');
return;
}
const result = hitokotos[Math.floor(Math.random() * hitokotos.length)];
// Send response
switch (format) {
case 'json':
res
.set({ 'Content-Type': `application/json charset=${encoding}` })
.send(iconv.encode(JSON.stringify(result), encoding));
break;
case 'text':
res
.set({ 'Content-Type': `text/plain; charset=${encoding}` })
.send(iconv.encode(result.hitokoto, encoding));
break;
case 'js':
res
.set({ 'Content-Type': `text/js charset=${encoding}` })
.send(
iconv.encode(
`document.querySeletor('${seletor}').innerText('${result.hitokoto}')`,
encoding,
),
);
break;
default:
res.status(400);
next(`Invalid format: ${format}`);
break;
}
next();
};
export default hitokoto;