-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathrequest.ts
More file actions
123 lines (104 loc) · 2.53 KB
/
request.ts
File metadata and controls
123 lines (104 loc) · 2.53 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import axios, {
type AxiosPromise,
type AxiosResponse,
type Method,
} from 'axios';
import type { Link, Token } from '../../types';
import { decryptValue } from '../comms';
import { rendererLogError } from '../logger';
import { getNextURLFromLinkHeader } from './utils';
/**
* Perform an unauthenticated API request
*
* @param url
* @param method
* @param data
* @returns
*/
export async function apiRequest(
url: Link,
method: Method,
data = {},
): Promise<AxiosPromise | null> {
const headers = await getHeaders(url);
return axios({ method, url, data, headers });
}
/**
* Perform an authenticated API request
*
* @param url
* @param method
* @param token
* @param data
* @param fetchAllRecords whether to fetch all records or just the first page
* @returns
*/
export async function apiRequestAuth(
url: Link,
method: Method,
token: Token,
data = {},
fetchAllRecords = false,
): AxiosPromise | null {
const headers = await getHeaders(url, token);
if (!fetchAllRecords) {
return axios({ method, url, data, headers });
}
let response: AxiosResponse | null = null;
let combinedData = [];
try {
let nextUrl: string | null = url;
while (nextUrl) {
response = await axios({ method, url: nextUrl, data, headers });
// If no data is returned, break the loop
if (!response?.data) {
break;
}
combinedData = combinedData.concat(response.data); // Accumulate data
nextUrl = getNextURLFromLinkHeader(response);
}
} catch (err) {
rendererLogError('apiRequestAuth', 'API request failed:', err);
throw err;
}
return {
...response,
data: combinedData,
} as AxiosResponse;
}
/**
* Return true if the request should be made with no-cache
*
* @param url
* @returns boolean
*/
function shouldRequestWithNoCache(url: string) {
const parsedUrl = new URL(url);
switch (parsedUrl.pathname) {
case '/api/v3/notifications':
case '/login/oauth/access_token':
case '/notifications':
return true;
default:
return false;
}
}
/**
* Construct headers for API requests
*
* @param username
* @param token
* @returns
*/
async function getHeaders(url: Link, token?: Token) {
const headers: Record<string, string> = {
Accept: 'application/json',
'Cache-Control': shouldRequestWithNoCache(url) ? 'no-cache' : '',
'Content-Type': 'application/json',
};
if (token) {
const decryptedToken = (await decryptValue(token)) as Token;
headers.Authorization = `token ${decryptedToken}`;
}
return headers;
}