-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
63 lines (56 loc) · 1.73 KB
/
index.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
const animals = [
'cat',
'dog',
'bird',
'panda',
'redpanda',
'koala',
'fox',
'whale',
'dolphin',
'kangaroo',
'rabbit',
'lion',
'bear',
'frog',
'duck',
'penguin',
'axolotl',
'capybara',
'hedgehog',
'turtle',
'narwhal',
'squirrel',
'fish',
'horse'
];
/**
* @typedef {Object} AnimalObject
* @property {string} type
* @property {string} animal
* @property {string} image
* @property {string} fact
* @property {string} image_id
* @property {string} fact_id
*/
module.exports = {
/**
* Returns an image and a fact of the specified animal type(s).
* @param {string | string[]} [type='random'] The animal type(s).
* @returns {AnimalObject | AnimalObject[]} The data object.
*/
async getAsync(type = 'random') {
const isArray = Array.isArray(type);
if ((typeof type !== 'string' && !isArray) || isArray && (type = type.flat()) && !type.every(t => typeof t === 'string')) throw new TypeError("'type' must be a string or an array of strings");
type = type === 'random' ? animals[Math.floor(Math.random() * animals.length)] : !isArray ? type.toLowerCase() : [...new Set(type.map(t => t.toLowerCase()))];
if (!isArray && !animals.includes(type)) throw new TypeError(`'${type}' is not a valid type, the valid types are: ${animals.join(', ')}, random`);
if (isArray) return Promise.all(type.map(t => this.getAsync(t)));
try {
const animalResponse = await fetch(`https://api.animality.xyz/all/${type}`).then(res => res.json());
const { animal, image, fact, image_id, fact_id } = animalResponse;
return { type, animal, image, fact, image_id, fact_id };
} catch (err) {
throw new Error(`Failed to get type '${type}' from API:\n${err}`);
}
}
};