-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
176 lines (162 loc) · 4.27 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import 'dotenv/config';
import express, { Application } from 'express';
import helmet from 'helmet';
import axios, { AxiosError } from 'axios';
import { createClient } from 'redis';
import path from 'path';
import console from 'console';
import { compileFile } from 'pug';
const authToken = process.env.GENIUS_TOKEN;
const port: string = process.env.PORT || '3000';
const app: Application = express();
const redisClient = createClient({
url: process.env.REDIS_TLS_URL,
socket: { tls: process.env.TLS !== 'false', rejectUnauthorized: false },
});
redisClient.on('error', (err) => {
console.log('Redis error', err);
});
app.use((req, _res, next) => {
const log: string[] = [];
log.push(req.method);
log.push(req.path);
log.push(req.ip);
log.push(req.socket.remoteAddress);
const headers = Object.entries(req.headers);
headers.forEach(([key, value]) => {
log.push(`${key}: ${value}`);
});
console.log(log.join(' | '));
next();
});
app.use(express.static(path.resolve('./public')));
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
scriptSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'https://images.genius.com'],
fontSrc: ["'self'", 'https://fonts.gstatic.com'],
},
},
}),
);
app.use(express.json());
const geniusAPI = axios.create({
baseURL: 'https://api.genius.com',
headers: {
Authorization: `Bearer ${authToken}`,
},
});
app.get('/api/search', async (req, res) => {
const { q: query, page } = req.query;
try {
const { data } = await geniusAPI.get(`/search?q=${query}&page=${page}`);
const songs = data.response.hits.map((hit) => {
const {
song_art_image_thumbnail_url: songArt,
title_with_featured: title,
primary_artist: { name: artistName },
id,
} = hit.result;
return {
songArt,
title,
artistName,
id,
};
});
res.json(songs);
} catch (error) {
res.status(500).json({ ...error.response.data });
}
});
async function getLyrics(id: string) {
const cachedLyrics = await redisClient.get(`lyrics:${id}`);
if (cachedLyrics) {
try {
return JSON.parse(cachedLyrics);
} catch (error) {
redisClient.del(`lyrics:${id}`);
}
}
const { data } = await geniusAPI.get(`/songs/${id}?text_format=plain`);
const {
song: {
lyrics,
artist_names: artistNames,
song_art_image_thumbnail_url: songArt,
title,
},
} = data.response;
const lyricsData = {
plain: lyrics.plain,
artists: artistNames,
songArt,
title,
};
await redisClient.setEx(
`lyrics:${id}`,
60 * 60 * 48,
JSON.stringify(lyricsData),
);
return lyricsData;
}
app.get('/api/lyrics/:id', async (req, res) => {
const { id } = req.params;
try {
const lyricsData = await getLyrics(id);
res.json(lyricsData);
} catch (error) {
console.log(error);
res.status(500).json(error);
}
});
app.get('/song/:id', async (req, res) => {
try {
const { id } = req.params;
const songTemplate = compileFile(path.resolve('./views/song.pug'));
const lyricsData = await getLyrics(id);
res.send(songTemplate({ song: { ...lyricsData } }));
} catch (error) {
const errorTemplate = compileFile(path.resolve('./views/error.pug'));
if (error instanceof AxiosError) {
res.status(error.response.status || 500).send(
errorTemplate({
data: {
status: error.response.status || 500,
message: error.response.statusText || 'Internal Server Error',
},
}),
);
} else {
res.status(500).send(
errorTemplate({
data: {
status: 500,
message: 'Internal Server Error',
},
}),
);
}
}
});
app.use((_req, res) => {
const errorTemplate = compileFile(path.resolve('./views/error.pug'));
res.status(404).send(
errorTemplate({
data: {
status: 404,
message: 'Not Found',
},
}),
);
});
app.listen(port, async () => {
console.time('Redis connected');
await redisClient.connect();
console.timeEnd('Redis connected');
console.log(`Server listening on port ${port}`);
});