-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (70 loc) · 1.99 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
69
70
71
72
const Koa = require('koa')
const router = require('koa-route')
const ratelimit = require('koa-ratelimit')
const Redis = require('ioredis')
const pug = require('pug')
const path = require('path')
const { argv } = require('yargs')
const {
CollegiateDictionary,
LearnersDictionary,
WordNotFoundError
} = require('mw-dict')
const { COLLEGIATE_DICT_API_KEY, LEARNERS_DICT_API_KEY } = require('./config')
const app = new Koa()
const collegiateDict = new CollegiateDictionary(COLLEGIATE_DICT_API_KEY)
const learnersDict = new LearnersDictionary(LEARNERS_DICT_API_KEY)
const render = pug.compileFile(path.join(__dirname, 'index.pug'))
app.use(
ratelimit({
db: new Redis(),
duration: 60000,
max: 20
})
)
async function lookup(dict, word) {
let results = await dict.lookup(word)
results = results.filter(r => r.word == word)
let output = results.map(
({ word, functional_label, pronunciation, definition }) => {
let html = `<h1>${word}</h1><p><em>${functional_label}</em></p>${render({
definition
})}`
return {
word,
pronunciation,
html
}
}
)
return output
}
app.use(
router.post('/word/:word', async (ctx, word) => {
try {
ctx.type = 'application/json'
let collegiateResult = await lookup(collegiateDict, word)
let learnersResult = await lookup(learnersDict, word)
let words = learnersResult.map(result => result.word)
let output = collegiateResult.map(result => {
let index = words.indexOf(result.word)
if (index > -1) {
result.html = learnersResult[index].html + '<hr/>' + result.html
}
return result
})
ctx.body = JSON.stringify(output)
} catch (e) {
if (e instanceof WordNotFoundError) {
ctx.status = 404
ctx.body = 'Word not found.'
} else {
console.log(e.message)
ctx.status = 500
ctx.body = 'Error'
}
}
})
)
app.listen(argv.port || 80)
console.log(`listening on port ${argv.port}`)