-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
62 lines (53 loc) · 1.93 KB
/
server.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 nodeJsonDb = require('node-json-db');
const express = require('express');
var cors = require('cors');
const app = express()
app.use(cors());
app.use(express.json());
const port = 3000; // change to whatever you like
const db = new nodeJsonDb.JsonDB(new nodeJsonDb.Config("db", true, false, '/'));
app.post('/:user', async function (req, res) {
const user = req.params.user;
const url = req.body.url;
const host = req.body.host;
if (host !== undefined) {
try {
const data = await db.getData(`/${user}/page/${host}`);
res.status(200).send({ page: data });
} catch {
res.status(404).send({ error: 'User not found' });
}
} else {
try {
const data = await db.getData(`/${user}/time/${Buffer.from(url).toString('base64')}`);
res.status(200).send({ time: data });
} catch {
res.status(404).send({ error: 'User or url not found' });
}
}
});
app.put('/:user', async function (req, res) {
const user = req.params.user;
const url = req.body.url;
const host = new URL(url).host;
const time = req.body.time; // not in base64
if (time !== undefined) {
try {
await db.push(`/${user}/time/${Buffer.from(url).toString('base64')}`, time);
res.status(200).send({ msg: 'Time saved' });
} catch (e) {
console.log(e)
res.status(500).send({ error: 'Something went wrong, please open an issue on https://github.com/Philip2809/where-was-i' });
}
} else {
try {
await db.push(`/${user}/page/${host}`, url);
res.status(200).send({ msg: 'Latest page saved' });
} catch {
res.status(500).send({ error: 'Something went wrong, please open an issue on https://github.com/Philip2809/where-was-i' });
}
}
});
app.listen(port, () => {
console.log(`Where Was I? running on port ${port}`)
})