/
main.ts
109 lines (87 loc) · 2.73 KB
/
main.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import Express from "express";
import ExpressRedisCache from "express-redis-cache";
import Redis from "redis";
import * as Config from "./config";
import * as Methods from "./methods";
// Helper functions.
const sendJSON = (res: Express.Response, data: object | string) => {
if (typeof data === 'object')
data = JSON.stringify(data);
res.set('Content-Type', 'application/json');
res.send(data);
}
const handleGetError = (res: Express.Response, next: Express.NextFunction, error: any) => {
if (error.statusCode == 404) {
res.status(404);
sendJSON(res, { error: 'not_found' });
} else {
next();
}
}
// Create Express.js app.
const app = Express();
// Set up Redis caching on all routes.
const redis = Redis.createClient(Config.redisUrl);
const cache = ExpressRedisCache({
client: redis,
prefix: 'dso',
expire: 60*60*24, // Cache entries expire after one day.
})
app.use(cache.route());
// Define routes for REST API.
app.get('/', (req, res) => res.send('Data Science Ontology API'));
app.get('/concept/_random',
(req, res) => {
Methods.randomConcept().then(body => sendJSON(res, body));
});
app.get('/annotation/_random',
(req, res) => {
Methods.randomAnnotation().then(body => sendJSON(res, body));
});
app.get('/concept/:id',
(req, res, next) => {
let { id } = req.params;
Methods.getConcept(id)
.then(body => sendJSON(res, body))
.catch(error => handleGetError(res, next, error));
});
app.get('/annotation/:lang/:pkg/:id',
(req, res, next) => {
let { lang, pkg, id } = req.params;
Methods.getAnnotation(lang, pkg, id)
.then(body => sendJSON(res, body))
.catch(error => handleGetError(res, next, error));
});
app.get('/concepts',
(req, res) => {
Methods.listConcepts().then(body => sendJSON(res, body));
});
app.get('/annotations',
(req, res) => {
Methods.listAnnotations().then(body => sendJSON(res, body));
});
app.get('/counts',
(req, res) => {
Methods.counts().then(body => sendJSON(res, body));
});
app.get('/search/concept/:text',
(req, res) => {
let { text } = req.params;
Methods.searchConcepts(text).then(body => sendJSON(res, body));
});
app.get('/search/annotation/:text',
(req, res) => {
let { text } = req.params;
Methods.searchAnnotations(text).then(body => sendJSON(res, body));
});
app.get('/_cache/annotation/:lang/:pkg/:id',
(req, res, next) => {
let { lang, pkg, id } = req.params;
const _id = `annotation/${lang}/${pkg}/${id}`;
Methods.getCache(_id)
.then(body => sendJSON(res, body))
.catch(error => handleGetError(res, next, error));
});
// Start the app!
app.listen(Config.port, () => console.log(
`Data Science Ontology proxy server listening on port ${Config.port}`));