-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedia.js
More file actions
42 lines (37 loc) · 1009 Bytes
/
media.js
File metadata and controls
42 lines (37 loc) · 1009 Bytes
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
import iconv from 'iconv-lite';
import { isCategoryInclude } from '../lib/utils.js';
const media = ({ resources }, req, res, next) => {
const {
category = 'all',
format = 'raw',
encoding = 'utf-8',
} = req.parsedParams;
// Selete random resource
const files = [];
Object.entries(resources[req.baseUrl]).forEach(([key, value]) => {
if (isCategoryInclude(key, category)) files.push(...value);
});
if (files.length === 0) {
res.status(500);
next('No matching resource found');
return;
}
const result = files[Math.floor(Math.random() * files.length)];
// Send response
switch (format) {
case 'raw':
res.redirect(302, result.url);
break;
case 'json':
res
.set({ 'Content-Type': `application/json charset=${encoding}` })
.send(iconv.encode(JSON.stringify(result), encoding));
break;
default:
res.status(400);
next(`Invalid format: ${format}`);
break;
}
next();
};
export default media;