-
Notifications
You must be signed in to change notification settings - Fork 116
/
apiClient.ts
244 lines (215 loc) · 6.95 KB
/
apiClient.ts
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import fetch, { Request, Response } from 'node-fetch';
import { NylasConfig, OverridableNylasConfig } from './config.js';
import {
NylasApiError,
NylasOAuthError,
NylasSdkTimeoutError,
} from './models/error.js';
import { objKeysToCamelCase, objKeysToSnakeCase } from './utils.js';
import { SDK_VERSION } from './version.js';
import * as FormData from 'form-data';
/**
* Options for a request to the Nylas API
* @property path The path to the API endpoint
* @property method The HTTP method to use
* @property headers Additional headers to send with the request
* @property queryParams Query parameters to send with the request
* @property body The body of the request
* @property overrides Overrides to the default Nylas API client configuration
* @ignore Not for public use
*/
export interface RequestOptionsParams {
path: string;
method: string;
headers?: Record<string, string>;
queryParams?: Record<string, any>;
body?: any;
form?: FormData;
overrides?: OverridableNylasConfig;
}
/**
* Options for building a request for fetch to understand
* @property path The path to the API endpoint
* @property method The HTTP method to use
* @property headers Additional headers to send with the request
* @property url The URL of the request
* @property body The body of the request
* @property overrides Overrides to the default Nylas API client configuration
* @ignore Not for public use
*/
interface RequestOptions {
path: string;
method: string;
headers: Record<string, string>;
url: URL;
body?: any;
overrides?: Partial<NylasConfig>;
}
/**
* The API client for communicating with the Nylas API
* @ignore Not for public use
*/
export default class APIClient {
/**
* The API key to use for authentication
*/
apiKey: string;
/**
* The URL to use for communicating with the Nylas API
*/
serverUrl: string;
/**
* The timeout for requests to the Nylas API, in seconds
*/
timeout: number;
/**
* Additional headers to send with outgoing requests
*/
headers: Record<string, string>;
constructor({ apiKey, apiUri, timeout, headers }: Required<NylasConfig>) {
this.apiKey = apiKey;
this.serverUrl = apiUri;
this.timeout = timeout * 1000; // fetch timeout uses milliseconds
this.headers = headers;
}
private setRequestUrl({
overrides,
path,
queryParams,
}: RequestOptionsParams): URL {
const url = new URL(`${overrides?.apiUri || this.serverUrl}${path}`);
return this.setQueryStrings(url, queryParams);
}
private setQueryStrings(
url: URL,
queryParams?: Record<string, unknown>
): URL {
if (queryParams) {
const snakeCaseParams = objKeysToSnakeCase(queryParams, ['metadataPair']);
for (const [key, value] of Object.entries(snakeCaseParams)) {
if (key == 'metadataPair') {
// The API understands a metadata_pair filter in the form of:
// <key>:<value>
const metadataPair: string[] = [];
for (const item in value as Record<string, string>) {
metadataPair.push(
`${item}:${(value as Record<string, string>)[item]}`
);
}
url.searchParams.set('metadata_pair', metadataPair.join(','));
} else {
url.searchParams.set(key, value as string);
}
}
}
return url;
}
private setRequestHeaders({
headers,
overrides,
}: RequestOptionsParams): Record<string, string> {
const mergedHeaders: Record<string, string> = {
...headers,
...this.headers,
...overrides?.headers,
};
return {
Accept: 'application/json',
'User-Agent': `Nylas Node SDK v${SDK_VERSION}`,
Authorization: `Bearer ${overrides?.apiKey || this.apiKey}`,
...mergedHeaders,
};
}
private async sendRequest(options: RequestOptionsParams): Promise<Response> {
const req = this.newRequest(options);
const controller: AbortController = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
throw new NylasSdkTimeoutError(req.url, this.timeout);
}, this.timeout);
try {
const response = await fetch(req, { signal: controller.signal });
clearTimeout(timeout);
if (typeof response === 'undefined') {
throw new Error('Failed to fetch response');
}
if (response.status > 299) {
const text = await response.text();
let error: Error;
try {
const parsedError = JSON.parse(text);
const camelCaseError = objKeysToCamelCase(parsedError);
// Check if the request is an authentication request
const isAuthRequest =
options.path.includes('connect/token') ||
options.path.includes('connect/revoke');
if (isAuthRequest) {
error = new NylasOAuthError(camelCaseError, response.status);
} else {
error = new NylasApiError(camelCaseError, response.status);
}
} catch (e) {
throw new Error(
`Received an error but could not parse response from the server: ${text}`
);
}
throw error;
}
return response;
} catch (error) {
clearTimeout(timeout);
throw error;
}
}
requestOptions(optionParams: RequestOptionsParams): RequestOptions {
const requestOptions = {} as RequestOptions;
requestOptions.url = this.setRequestUrl(optionParams);
requestOptions.headers = this.setRequestHeaders(optionParams);
requestOptions.method = optionParams.method;
if (optionParams.body) {
requestOptions.body = JSON.stringify(
objKeysToSnakeCase(optionParams.body)
);
requestOptions.headers['Content-Type'] = 'application/json';
}
if (optionParams.form) {
requestOptions.body = optionParams.form;
requestOptions.headers = {
...requestOptions.headers,
...optionParams.form.getHeaders(),
};
}
return requestOptions;
}
newRequest(options: RequestOptionsParams): Request {
const newOptions = this.requestOptions(options);
return new Request(newOptions.url, {
method: newOptions.method,
headers: newOptions.headers,
body: newOptions.body,
});
}
async requestWithResponse<T>(response: Response): Promise<T> {
const text = await response.text();
try {
const responseJSON = JSON.parse(text);
return objKeysToCamelCase(responseJSON);
} catch (e) {
throw new Error(`Could not parse response from the server: ${text}`);
}
}
async request<T>(options: RequestOptionsParams): Promise<T> {
const response = await this.sendRequest(options);
return this.requestWithResponse(response);
}
async requestRaw(options: RequestOptionsParams): Promise<Buffer> {
const response = await this.sendRequest(options);
return response.buffer();
}
async requestStream(
options: RequestOptionsParams
): Promise<NodeJS.ReadableStream> {
const response = await this.sendRequest(options);
return response.body;
}
}