Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
402 lines (357 loc) · 10.5 KB
/
Copy pathindex.ts
File metadata and controls
402 lines (357 loc) · 10.5 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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/**
* Created by Ivo Meißner on 05.08.17.
*
* @flow
*/
import 'isomorphic-fetch';
import 'isomorphic-form-data';
import {DocumentNode} from 'graphql/language/ast';
import {print} from 'graphql/language/printer';
const REFRESH_TOKEN_KEY = ':auth:refreshToken';
const REFRESH_TOKEN_EXPIRES_KEY = ':auth:refreshTokenExpires';
const ACCESS_TOKEN_KEY = ':auth:accessToken';
const ACCESS_TOKEN_EXPIRES_KEY = ':auth:accessTokenExpires';
const DEFAULT_NAMESPACE = 'slicknode';
declare global {
namespace NodeJS {
interface Global {
localStorage: Storage;
}
}
}
// @TODO: Improve typing
// We overwrite FormData to support Buffer | Blob | File | string as file uploads
interface FormData {
append(name: string, value: Uploadable, fileName?: string): void;
delete(name: string): void;
get(name: string): FormDataEntryValue | null;
getAll(name: string): FormDataEntryValue[];
has(name: string): boolean;
set(name: string, value: string | Blob, fileName?: string): void;
forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void;
}
/**
* Interface for custom storage
*/
export interface Storage {
getItem(keyName: string): string | null;
setItem(keyName: string, keyValue: string): void;
removeItem(keyName: string): void;
clear(): void;
}
export type AuthTokenSet = {
accessToken: string,
accessTokenLifetime: number,
refreshToken: string,
refreshTokenLifetime: number
}
export type ResponseError = {
message: string,
locations?: Array<{
line: number,
column: number
}>
}
export type Response<TData = {[key: string]: any}> = {
data: TData | null,
errors?: ResponseError[]
}
export type Authenticator = (client: Client) => Promise<AuthTokenSet>;
export type Uploadable = File | Blob | Buffer | string;
export type UploadableMap = {[key: string]: Uploadable};
export type ClientOptions = {
/**
* The slicknode GraphQL endpoint URL
*/
endpoint: string,
/**
* Headers to be sent with each request
*/
headers?: HeadersInit,
/**
* Options that are passed to the fetch() call
*/
options?: RequestInit,
/**
* The storage interface to store auth tokens, default is localStorage
*/
storage?: Storage,
/**
* The namespace under which auth tokens are stored
*/
namespace?: string,
/**
* Use a permanent access token for authentication
*/
accessToken?: string,
}
export const REFRESH_TOKEN_MUTATION = `mutation refreshToken($token: String!) {
refreshAuthToken(input: {refreshToken: $token}) {
accessToken
refreshToken
accessTokenLifetime
refreshTokenLifetime
}
}`;
export const LOGOUT_MUTATION = `mutation logout($refreshToken: String) {
logoutUser(input:{refreshToken:$refreshToken}) {
success
}
}`;
/**
* In memory storage
*/
export class MemoryStorage {
values: {[key: string]: string};
constructor() {
this.values = {};
}
getItem(keyName: string): string | null {
return this.values.hasOwnProperty(keyName) ? this.values[keyName] : null;
}
setItem(keyName: string, keyValue: string): void {
this.values[keyName] = keyValue;
}
removeItem(keyName: string): void {
delete this.values[keyName];
}
clear(): void {
this.values = {};
}
}
export default class Client {
options: ClientOptions;
storage: Storage;
namespace: string;
/**
* Constructor
* @param options
*/
constructor(options: ClientOptions) {
if (!options || typeof options.endpoint !== 'string') {
throw new Error('You have to provide the endpoint of the GraphQL server to the client');
}
this.options = options;
this.namespace = options.namespace || DEFAULT_NAMESPACE;
this.storage = options.storage || global.localStorage || new MemoryStorage();
}
/**
* Sends a query to the GraphQL endpoint and returns a promise that
* resolves to the returned data
*
* @param query
* @param variables
* @param operationName
* @param files
* @returns {Promise.<void>}
*/
async fetch<TData = {[field: string]: any}>(
query: string | DocumentNode,
variables: {[key: string]: any} = {},
operationName: string | null = null,
files: UploadableMap = {}
): Promise<Response<TData>> {
const authHeaders = query !== REFRESH_TOKEN_MUTATION ? await this.getAuthHeaders() : {};
const gqlQueryString = typeof query === 'string' ? query : print(query);
const config: RequestInit = {
method: 'POST',
headers: {
...authHeaders,
...(this.options.headers || {})
},
credentials: 'same-origin',
};
// We have files, send request as multipart
if (files && Object.keys(files).length > 0) {
const data = new FormData() as FormData;
Object.keys(files).forEach((name => {
const file = files[name];
// If we have buffer or string, add filename
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(file) || typeof file === 'string') {
// $FlowFixMe:
data.append(name, file, 'data.bin');
} else {
// $FlowFixMe:
data.append(name, file);
}
}));
data.append('query', gqlQueryString);
data.append('variables', JSON.stringify(variables || {}));
if (operationName) {
data.append('operationName', operationName);
}
config.body = data;
} else {
// Send as normal POST request
config.body = JSON.stringify({
query: gqlQueryString,
variables: variables || {},
...(operationName ? {operationName} : {})
});
config.headers = {
...config.headers,
'Content-Type': 'application/json',
'Accept': 'application/json'
};
}
const result = await fetch(
this.options.endpoint,
config
);
return await result.json();
}
/**
* Returns a promise that resolves the response of the authenticator
*
* @param authenticator
* @returns {Promise.<*>}
*/
async authenticate(authenticator: Authenticator): Promise<AuthTokenSet> {
const tokenSet = await authenticator(this);
this.setAuthTokenSet(tokenSet);
return tokenSet;
}
/**
* Returns true if the client has a valid access token
*
* @returns {boolean}
*/
hasAccessToken(): boolean {
return Boolean(this.getAccessToken());
}
/**
* Returns true if the client has a valid refresh token
*
* @returns {boolean}
*/
hasRefreshToken(): boolean {
return Boolean(this.getRefreshToken());
}
/**
* Updates the auth token set
* @param token
*/
setAuthTokenSet(token: AuthTokenSet): void {
this.setAccessToken(token.accessToken);
this.setAccessTokenExpires(token.accessTokenLifetime * 1000 + Date.now());
this.setRefreshToken(token.refreshToken);
this.setRefreshTokenExpires(token.refreshTokenLifetime * 1000 + Date.now());
}
/**
* Stores the refreshToken in the storage of the client
* @param token
*/
setRefreshToken(token: string) {
const key = this.namespace + REFRESH_TOKEN_KEY;
this.storage.setItem(key, token);
}
/**
* Returns the refresh token, NULL if none was stored yet
* @returns {string|null}
*/
getRefreshToken(): string | null {
if ((this.getRefreshTokenExpires() || 0) < Date.now()) {
return null;
}
const key = this.namespace + REFRESH_TOKEN_KEY;
return this.storage.getItem(key);
}
/**
* Sets the time when the auth token expires
*/
setAccessTokenExpires(timestamp: number | null) {
const key = this.namespace + ACCESS_TOKEN_EXPIRES_KEY;
if (timestamp) {
this.storage.setItem(key, String(timestamp));
} else {
this.storage.removeItem(key);
}
}
/**
* Returns the UNIX Timestamp when the refresh token expires
* @returns {number|null}
*/
getRefreshTokenExpires(): number | null {
const key = this.namespace + REFRESH_TOKEN_EXPIRES_KEY;
const expires = this.storage.getItem(key);
return expires ? parseInt(expires, 10) : null;
}
/**
* Sets the time when the auth token expires
*/
setRefreshTokenExpires(
timestamp: number | null
): void {
const key = this.namespace + REFRESH_TOKEN_EXPIRES_KEY;
this.storage.setItem(key, String(timestamp));
}
/**
* Returns the UNIX Timestamp when the access token expires
* @returns {number|null}
*/
getAccessTokenExpires(): number | null {
const key = this.namespace + ACCESS_TOKEN_EXPIRES_KEY;
const expires = this.storage.getItem(key) || null;
return expires ? parseInt(expires, 10) : null;
}
/**
* Writes the access token to storage
* @param token
*/
setAccessToken(token: string): void {
const key = this.namespace + ACCESS_TOKEN_KEY;
this.storage.setItem(key, token);
}
/**
* Returns the access token, NULL if no valid token was found
* @returns {null}
*/
getAccessToken(): string | null {
// Check if is expired
if ((this.getAccessTokenExpires() || 0) < Date.now()) {
return null;
}
const key = this.namespace + ACCESS_TOKEN_KEY;
return this.storage.getItem(key) || null;
}
/**
* Clears all tokens in the storage
*/
async logout(): Promise<void> {
const refreshToken = this.getRefreshToken();
this.storage.removeItem(this.namespace + REFRESH_TOKEN_KEY);
this.storage.removeItem(this.namespace + REFRESH_TOKEN_EXPIRES_KEY);
this.storage.removeItem(this.namespace + ACCESS_TOKEN_KEY);
this.storage.removeItem(this.namespace + ACCESS_TOKEN_EXPIRES_KEY);
await this.fetch(LOGOUT_MUTATION, {refreshToken});
}
/**
* Returns the headers that are required to authenticate at the GraphQL endpoint.
* If no access tokens are available, an attempt is made to retrieve it from the backend
* with the refreshToken
*/
async getAuthHeaders(): Promise<HeadersInit> {
let accessToken = this.options.accessToken || this.getAccessToken();
const refreshToken = this.getRefreshToken();
// We have no token, try to get it from API
if (!accessToken && refreshToken) {
// We have refresh token but expired auth token. Refresh auth token set.
const result = await this.fetch<{refreshAuthToken: AuthTokenSet | null}>(
REFRESH_TOKEN_MUTATION,
{token: refreshToken}
);
if (result && result.data && result.data.refreshAuthToken) {
this.setAuthTokenSet(result.data.refreshAuthToken);
accessToken = this.getAccessToken();
} else {
this.logout();
}
}
if (accessToken) {
return {
Authorization: `Bearer ${accessToken}`
};
}
return {};
}
}