UNPKG

1.29 kBPlain TextView Raw
1import fetch from 'node-fetch';
2
3/** Custom post function based on node-fetch */
4export async function post(
5 apiPath: string,
6 apiKey: string,
7 sendObj: object,
8 logStuff: boolean,
9): Promise<void> {
10 const postData = JSON.stringify(sendObj);
11 try {
12 const response = await fetch(apiPath, {
13 method: 'POST',
14 body: postData,
15 headers: {
16 'Content-Type': 'application/json',
17 'Content-Length': String(postData.length),
18 Authorization: apiKey,
19 },
20 });
21
22 if (logStuff) {
23 console.log('BLAPI: posted to', apiPath);
24 console.log('BLAPI: statusCode:', response.status, response.statusText);
25 console.log('BLAPI: headers:', response.headers.raw());
26 // it's text because text accepts both json and plain text, while json only supports json
27 console.log('BLAPI: data:', response.text());
28 }
29 } catch (e) {
30 console.error('BLAPI:', e);
31 throw new Error(`Request to ${apiPath} failed with ${e}`);
32 }
33}
34/** Custom get function based on node-fetch */
35export async function get<T>(url: string): Promise<T> {
36 try {
37 const response = await fetch(url);
38 return response.json();
39 } catch (e) {
40 console.error('BLAPI:', e);
41 throw new Error(`Request to ${url} failed with Errorcode ${e}`);
42 }
43}