-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient.ts
58 lines (52 loc) · 1.57 KB
/
client.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
import * as apollo from '@apollo/client/core/index.js';
import { ApolloError } from '../service/error.svc.ts';
export interface ApolloHelper {
mutate<T, V extends apollo.OperationVariables>(
mutation: apollo.DocumentNode,
variables?: V,
): Promise<apollo.FetchResult<T>>;
query<T, V extends apollo.OperationVariables | undefined = undefined>(
query: apollo.DocumentNode,
variables?: V,
): Promise<apollo.ApolloQueryResult<T>>;
}
export const createApollo = (url: string) =>
new apollo.ApolloClient({
cache: new apollo.InMemoryCache({
addTypename: false,
}),
headers: {
'User-Agent': `hdcli/${process.env.npm_package_version ?? 'unknown'}`,
},
link: apollo.ApolloLink.from([
new apollo.HttpLink({
uri: url,
}),
]),
});
export class ApolloClient implements ApolloHelper {
#apollo: apollo.ApolloClient<apollo.NormalizedCacheObject>;
constructor(url: string) {
this.#apollo = createApollo(url);
}
async mutate<T, V extends apollo.OperationVariables>(mutation: apollo.DocumentNode, variables?: V) {
try {
return await this.#apollo.mutate<T, V>({
mutation,
variables,
});
} catch (error: unknown) {
throw new ApolloError('GraphQL mutation failed', error);
}
}
async query<T, V extends apollo.OperationVariables | undefined>(query: apollo.DocumentNode, variables?: V) {
try {
return await this.#apollo.query<T>({
query,
variables,
});
} catch (error) {
throw new ApolloError('GraphQL query failed', error);
}
}
}