-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
68 lines (57 loc) · 1.8 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
63
64
65
66
67
68
const express = require('express')
const logfmt = require('logfmt')
const merge = require('merge')
const cors = require('cors')
const translate = require('wikipedia-translator')
const wikipedias = require('wikipedias')
const geojsonify = require('./lib/geojsonify')
const app = module.exports = express()
if (process.env.NODE_ENV !== 'test') app.use(logfmt.requestLogger())
app.use(express.static('public'))
app.set('view engine', 'jade')
app.get('/', cors(), function (req, res) {
const locals = {
wikipedias: wikipedias,
hostname: req.hostname
}
// Support the old URL format
if (req.query.query) {
const url = require('url').format({
pathname: '/search',
query: req.query
})
return res.redirect(url)
}
res.render('index', locals)
})
app.get('/search', cors(), function (req, res) {
const locals = {
wikipedias: wikipedias,
hostname: req.hostname
}
// Query param is required
if (!req.query || !req.query.query) {
return res.redirect('/')
}
// English is the default language
req.query.lang || (req.query.lang = 'en')
// Log it so we can watch the queries go by
if (process.env.NODE_ENV !== 'test') { logfmt.log(req.query) }
translate(req.query.query, req.query.lang, function (err, translation) {
if (err) console.error(err)
// "/search?query="+ t.word.toLowerCase() + "&lang=" + t.lang
if (req.query.format && req.query.format === 'geojson') {
res.json(geojsonify(translation.translations))
} else if (req.query.format && req.query.format === 'json') {
res.json(merge(locals, translation))
} else {
res.render('search', merge(locals, translation))
}
})
})
if (!module.parent) {
const port = process.env.PORT || 5000
app.listen(port, function () {
console.log('App running on port %s', port)
})
}