This repository was archived by the owner on Sep 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrequest.js
More file actions
55 lines (53 loc) · 1.67 KB
/
Copy pathrequest.js
File metadata and controls
55 lines (53 loc) · 1.67 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
const fetch = require('node-fetch');
const baseURL = 'https://www.guilded.gg/api';
/**
* Make a request to the api.
* @param {Object} options - The options for the request.
* @param {string} options.path - The path to go request.
* @param {*} options.data - The data to send.
* @param {string} [options.method='post'] - The method.
* @param {object} options.cookies - The cookies to send.
* @param {boolean} [options.json=true] - If you want to receive a JSON response.
* @param {boolean} [options.hardError=false] - Whether or not to throw an error if the request fails.
* @returns {Promise<object>} The response from the server.
* @private
*/
const request = async (options = {}) => {
let {
path,
cookies,
data: body = {},
method = 'post',
json = true,
hardError = false
} = options;
let data = {
method,
headers: {
'Content-Type': 'application/json',
Cookie: cookies.join(', ')
}
};
if (method === 'post') data.body = body;
try {
let res = await fetch(`${baseURL}/${path}`, data);
cookies = res.headers.raw()['set-cookie'];
let fin = {
res: json ? await res.json() : await res.text(),
cookies,
ok: res.ok,
status: res.status
};
return fin;
} catch (e) {
if (hardError)
throw new Error(`There was an ${e.name || 'Error'} making a ${method} request to ${path}.`);
else return {
res: json ? {message: e.message} : e.message,
cookies,
ok: false,
status: e.name
}
}
};
module.exports = request;