-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_api.js
45 lines (40 loc) · 1.33 KB
/
web_api.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
const express = require('express');
class WebAPI {
constructor(client, nconf) {
this.client = client;
this.nconf = nconf;
this.app = express();
this.app.use(express.json());
this.app.use((req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (apiKey === this.nconf.get("API_KEY")) {
next();
} else {
res.status(401).send({ "error": "Unauthorized" });
}
});
this.app.post('/message', async (req, res) => {
const { message, recipient } = req.body;
this.client.getChatById(recipient)
.then(chat => chat.sendMessage(message))
.then(message => res.send(message.id))
.catch(error => res.send({ "error": error.message.split("\n")[0] }));
});
this.app.get('/', (req, res) => {
try {
res.send(this.client.info);
}
catch (err) {
console.error(err);
res.send({ "error": err.message.split("\n")[0] });
}
});
const api_port = nconf.get("API_PORT");
this.app.listen(api_port, () => {
console.log(`API listening on port ${api_port}`);
});
}
}
module.exports = {
WebAPI: WebAPI,
};