This repository has been archived by the owner on Aug 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 243
/
server.js
72 lines (64 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
63
64
65
66
67
68
69
70
71
72
const {
search,
getLatestCharts,
getSongsSample,
getNbSongs,
trackClick
} = require('./src/utils/db');
const Express = require('express');
const { Server } = require('http');
const Fs = require('fs');
const Path = require('path');
const express = Express();
const server = Server(express);
const port = process.env.PORT || 3000;
// Production should use a reverse proxy (e.g. nginx; I'm using caddy)
// that redirects /search to /index.html, and /api to process.env.PORT
if (process.env.NODE_ENV != 'production') {
express.use(Express.static(Path.resolve(process.env.NODE_DIR || 'dist')));
express.get('/search', (req, res) => res.sendFile(Path.resolve(__dirname, 'dist', 'index.html')));
express.get('/random', (req, res) => res.sendFile(Path.resolve(__dirname, 'dist', 'index.html')));
}
express.get('/api/count', async (req, res) => {
try {
const count = await getNbSongs();
return res.send(count);
} catch (err) {
console.error(err.stack);
res.sendStatus(500);
}
});
express.get('/api/latest', async (req, res) => {
try {
const { from } = req.query;
const results = await getLatestCharts(from);
return res.json(results);
} catch (err) {
console.error(err.stack);
res.sendStatus(500);
}
});
express.get('/api/random', async (req, res) => {
try {
const results = await getSongsSample();
return res.json(results);
} catch (err) {
console.error(err.stack);
res.sendStatus(500);
}
});
express.get('/api/search', async (req, res) => {
try {
const { from, query } = req.query;
const results = await search(query, from);
return res.json(results);
} catch (err) {
console.error(err.stack);
res.sendStatus(500);
}
});
express.post('/api/click', async (req, res) => {
trackClick({ id: req.query.id }).catch(err => console.error(err.stack));
res.sendStatus(200);
});
server.listen(port, () => console.log(`Server: Listening to http://localhost:${port}`));