-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathrequest.ts
More file actions
176 lines (153 loc) · 3.85 KB
/
Copy pathrequest.ts
File metadata and controls
176 lines (153 loc) · 3.85 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import axios, {
type AxiosPromise,
type AxiosResponse,
type Method,
} from 'axios';
import type { ExecutionResult } from 'graphql';
import type { Link, Token } from '../../types';
import { decryptValue } from '../comms';
import { rendererLogError } from '../logger';
import type { TypedDocumentString } from './graphql/generated/graphql';
import { getNextURLFromLinkHeader } from './utils';
/**
* ExecutionResult with HTTP response headers
*/
export type ExecutionResultWithHeaders<T> = ExecutionResult<T> & {
headers: Record<string, string>;
};
/**
* 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;
}
/**
* Perform a GraphQL API request for account
*
* @param account
* @param query
* @param variables
* @returns
*/
export async function performGraphQLRequest<TResult, TVariables>(
url: Link,
token: Token,
query: TypedDocumentString<TResult, TVariables>,
...[variables]: TVariables extends Record<string, never> ? [] : [TVariables]
) {
const headers = await getHeaders(url, token);
return axios({
method: 'POST',
url,
data: {
query,
variables,
},
headers: headers,
}).then((response) => {
return {
...response.data,
headers: response.headers,
};
}) as Promise<ExecutionResultWithHeaders<TResult>>;
}
/**
* Perform a GraphQL API request using a raw query string instead of a TypedDocumentString.
*
* Useful for dynamically composed queries (e.g., merged queries built at runtime).
*/
export async function performGraphQLRequestString<TResult>(
url: Link,
token: Token,
query: string,
variables?: Record<string, unknown>,
): Promise<ExecutionResultWithHeaders<TResult>> {
const headers = await getHeaders(url, token);
return axios({
method: 'POST',
url,
data: {
query,
variables,
},
headers: headers,
}).then((response) => {
return {
...response.data,
headers: response.headers,
} as ExecutionResultWithHeaders<TResult>;
});
}
/**
* Return true if the request should be made with no-cache
*
* @param url
* @returns boolean
*/
export 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
*/
export 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;
}