-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (63 loc) · 1.93 KB
/
index.js
File metadata and controls
76 lines (63 loc) · 1.93 KB
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
const { get } = require('node:https');
const emojis = {
emojis: require('./data/emoji/collection/big.json'),
cats: require('./data/emoji/cat.json'),
foods: require('./data/emoji/food.json'),
hearts: require('./data/emoji/heart.json'),
circles: require('./data/emoji/circle.json'),
squares: require('./data/emoji/square.json'),
unicode: require('./data/emoji/collection/single.json'),
};
const endpoints = require('./data/endpoints.json');
const { name, version, devDependencies } = require('./package.json');
const httpOptions = {
method: 'GET',
headers: {
'User-Agent': `${name}/${version} (+https://github.com/sefinek/geoip2-api)${process.env.JEST_WORKER_ID && devDependencies?.jest ? ` jest/${devDependencies.jest.replace(/^[^0-9]*/, '')}` : ''}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'DNT': '1',
},
};
const getContent = url => new Promise((resolve, reject) => {
const req = get(url, httpOptions, res => {
if (res.statusCode !== 200) {
res.resume();
return reject(new Error(`Request failed with status code ${res.statusCode}`));
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
try {
resolve(JSON.parse(rawData));
} catch (err) {
reject(new Error(`Failed to parse JSON: ${err.message}`));
}
});
res.on('error', reject);
});
req.on('error', reject);
req.end();
});
class SefinekAPI {
constructor() {
for (const [key, endpoint] of Object.entries(endpoints)) {
this[key] = () => getContent(`https://api.sefinek.net/api/v2/random/${endpoint}`);
}
}
}
const getRandomElement = arr => arr[Math.floor(Math.random() * arr.length)];
const emojiGetters = {};
for (const [key, value] of Object.entries(emojis)) {
emojiGetters[key] = () => getRandomElement(value);
}
module.exports = {
...emojiGetters,
Kaomojis: SefinekAPI,
version,
};