-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.ts
More file actions
190 lines (173 loc) · 6.63 KB
/
index.ts
File metadata and controls
190 lines (173 loc) · 6.63 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
import {
ApolloClient,
ApolloError,
InMemoryCache,
useApolloClient,
useQuery as useApolloQuery,
type ApolloClientOptions,
type NormalizedCacheObject,
type OperationVariables,
type QueryOptions,
type ServerError,
type ServerParseError,
} from '@apollo/client';
import { Logger } from '@snapwp/core';
import { getGraphqlUrl } from '@snapwp/core/config';
import { QueryProvider as ApolloQueryProvider } from './query-provider';
import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
import type { QueryEngine } from '@snapwp/types';
export type clientType = ApolloClient< NormalizedCacheObject >;
export type clientOptionsType = ApolloClientOptions< NormalizedCacheObject >;
type ApolloQueryArgs< TData, TQueryVars extends Record< string, unknown > > = {
name: string;
query: TypedDocumentNode< TData, TQueryVars >;
options?: QueryOptions< TQueryVars, TData >;
};
/**
* An adapter for Apollo Client that implements the QueryEngine interface.
* This adapter provides methods for obtaining an Apollo Client instance, executing queries,
* and using queries as hooks.
*/
export class ApolloClientEngine implements QueryEngine< clientType > {
private readonly client: ApolloClient< NormalizedCacheObject >;
/**
* Creates a new instance of ApolloClientEngine.
* @param { ApolloClientOptions< NormalizedCacheObject > } options Optional ApolloClientOptions to configure the client instance.
*/
constructor( options?: ApolloClientOptions< NormalizedCacheObject > ) {
const defaultOptions: ApolloClientOptions< NormalizedCacheObject > = {
cache: new InMemoryCache(),
uri: getGraphqlUrl(),
};
const mergedOptions = {
...defaultOptions,
...( ( options as Partial<
ApolloClientOptions< NormalizedCacheObject >
> ) || {} ),
};
this.client = new ApolloClient( mergedOptions );
}
/**
* Returns ApolloClient instance.
*
* @return A instance of ApolloClient.
*/
getClient(): ApolloClient< NormalizedCacheObject > {
return this.client;
}
/**
* Returns an ApolloClient instance from a provided client or undefined.
* This method is useful when you need to use the ApolloClient hook.
* @param { ApolloClient< NormalizedCacheObject > } client An optional ApolloClient instance.
* @return The ApolloClient instance if provided; otherwise, undefined.
*/
useClient(
client: ApolloClient< NormalizedCacheObject > | undefined
): ApolloClient< NormalizedCacheObject > {
// eslint-disable-next-line react-hooks/rules-of-hooks -- This is a hook, so we need to use it in a React component.
return useApolloClient(
client || this.client
) as ApolloClient< NormalizedCacheObject >;
}
/**
* Executes a GraphQL query using the Apollo Client instance and writes the result to the cache.
* @param { Object } props - Object containing:
* @param { string } props.name - A string that uniquely identifies the query in the cache.
* @param { import('@apollo/client').DocumentNode | TypedDocumentNode< TData > } props.query - A GraphQL DocumentNode or TypedDocumentNode representing the query.
* @param { TQueryOptions } props.options - Optional query options compatible with Apollo's QueryOptions.
* @return A promise that resolves with the query data of type TData.
* @throws {Error} An error if the query fails, with enhanced error logging for ApolloErrors.
*/
async fetchQuery<
TData,
TQueryOptions extends Record< string, unknown >,
>( {
name,
query,
options,
}: ApolloQueryArgs< TData, TQueryOptions > ): Promise< TData > {
try {
const queryResult = await this.getClient().query< TData >( {
...options,
query,
// @todo: make this customizable. See https://github.com/rtCamp/headless/issues/461
fetchPolicy: 'no-cache',
} );
if ( queryResult.errors?.length ) {
queryResult.errors?.forEach( ( error ) => {
Logger.error( `Error fetching ${ name }: ${ error }` );
} );
}
return queryResult.data;
} catch ( error ) {
if ( error instanceof ApolloError ) {
logApolloErrors( error );
if ( error.networkError ) {
throw new Error(
getNetworkErrorMessage( error.networkError )
);
}
}
throw error;
}
}
/**
* Executes a GraphQL query as a React hook using Apollo's useQuery.
* @param { Object } props An object containing:
* @param { string } props.name - A string that uniquely identifies the query in the cache.
* @param { import('@apollo/client').DocumentNode | TypedDocumentNode< TData > } props.query - A GraphQL DocumentNode or TypedDocumentNode representing the query.
* @param { TQueryOptions } props.options - Optional query options compatible with Apollo's QueryHookOptions.
* @return The query result data of type TData.
*/
useQuery< TData, TQueryOptions extends Record< string, unknown > >( {
query,
options,
}: ApolloQueryArgs< TData, TQueryOptions > ): TData {
// eslint-disable-next-line react-hooks/rules-of-hooks -- This is a hook, so we need to use it in a React component.
return useApolloQuery< TData, OperationVariables >( query, options )
.data as TData;
}
QueryProvider = ApolloQueryProvider;
}
/**
* Logs Apollo errors by outputting error messages for GraphQL, client, and protocol errors.
* @param {ApolloError} error The ApolloError object containing error details.
*/
const logApolloErrors = ( error: ApolloError ): void => {
error.graphQLErrors.forEach( ( graphQLError ) => {
Logger.error( graphQLError.message );
} );
error.clientErrors.forEach( ( clientError ) => {
Logger.error( clientError.message );
} );
error.protocolErrors.forEach( ( protocolError ) => {
Logger.error( protocolError.message );
} );
};
/**
* Constructs a user-friendly network error message based on the type of network error.
* @param {Error | ServerParseError | ServerError} networkError The network error, which may be a generic Error, ServerParseError, or ServerError.
* @return A formatted string with the error message and status code.
*/
const getNetworkErrorMessage = (
networkError: Error | ServerParseError | ServerError
): string => {
let statusCode: number | undefined;
let errorMessage: string | undefined;
if ( networkError.name === 'ServerError' ) {
const serverError = networkError as ServerError;
statusCode = serverError.statusCode;
if ( typeof serverError.result === 'string' ) {
errorMessage = serverError.result;
} else {
errorMessage = serverError.result[ 'message' ];
}
} else if ( networkError.name === 'ServerParseError' ) {
const serverParseError = networkError as ServerParseError;
statusCode = serverParseError.statusCode;
errorMessage = serverParseError.message;
} else {
errorMessage = networkError.message;
}
return `Network error ${ errorMessage } (Status: ${ statusCode })`;
};