/
requests.ts
47 lines (42 loc) · 1.5 KB
/
requests.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
import 'cross-fetch/polyfill';
import { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { DocumentNode } from 'graphql';
import { request } from 'graphql-request';
import { Keychain } from '@daohaus/keychain-utils';
import { IFindQueryResult, QueryVariables } from '../types/query.types';
import { formatFetchError } from './fetchErrors';
type RequestDocument = string | DocumentNode;
export const graphFetch = async <T = unknown, V = QueryVariables>(
document: RequestDocument | TypedDocumentNode<T, V>,
url: string,
networkId: keyof Keychain,
variables?: V
): Promise<IFindQueryResult<T>> => {
const res = await request<T, V>(url, document, cleanVariables(variables));
return { data: res, networkId };
};
export const graphFetchList = async <T = unknown, V = QueryVariables>(
document: RequestDocument | TypedDocumentNode<T, V>,
url: string,
variables?: V
): Promise<T> => {
try {
return await request<T, V>(url, document, cleanVariables(variables));
} catch (err) {
throw formatFetchError({ type: 'SUBGRAPH_ERROR', errorObject: err });
}
};
const cleanVariables = <V = QueryVariables>(variables: V): V => {
return Object.fromEntries(
Object.entries(variables as Record<string, unknown>)
.filter(
([, value]) => value !== '' && value !== null && value !== undefined
)
.map(([key, value]) => [
key,
value === Object(value) && !Array.isArray(value)
? cleanVariables(value)
: value,
])
) as unknown as V;
};