-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (51 loc) · 1.56 KB
/
index.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
const fs = require('fs');
const os = require('os');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const RBT = require('icu-transliterator').RBT;
registerCustomTransliterators();
const app = express();
app.disable('x-powered-by');
let listenDefault = 'localhost';
let mountDir = '/';
configToolforge();
app.use(bodyParser.text({ type: '*/*' }));
const router = express.Router();
app.use(mountDir, router);
router.post('/:id', transliterate(RBT.FORWARD));
router.post('/:id/forward', transliterate(RBT.FORWARD));
router.post('/:id/reverse', transliterate(RBT.REVERSE));
app.listen(process.env.PORT || 3000, process.env.LISTENADDR || listenDefault);
function configToolforge() {
const matches = os.userInfo().username.match(/^tools\.(.+)$/);
if (matches) {
listenDefault = '0.0.0.0';
mountDir = '/' + matches[1];
app.use(cors());
}
}
function registerCustomTransliterators() {
const transliterators = __dirname + '/transliterators.json';
if (fs.existsSync(transliterators)) {
const t = require(transliterators);
t.forEach(function (obj) {
RBT.register(obj.name, obj.rules);
});
}
}
function transliterate(dir) {
return function(req, res) {
try {
let output = RBT(req.params.id, dir).transliterate(req.body);
if (req.headers['user-agent'] && req.headers['user-agent'].match(/^curl\//)) {
output += '\n';
}
res.set('Content-type', 'text/plain');
res.send(output);
} catch (e) {
console.error(e);
res.sendStatus(409);
}
}
}