The shared core for the highly customizable and versatile GraphQL client
npx @tessl/cli install tessl/npm-urql--core@6.0.00
# @urql/core
1
2
@urql/core is the foundational GraphQL client library that provides a highly customizable and versatile approach to GraphQL operations. It implements a modular exchange system for handling requests, caching, subscriptions, and other GraphQL client concerns, with full TypeScript support and framework-agnostic design.
3
4
## Package Information
5
6
- **Package Name**: @urql/core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @urql/core`
10
11
## Core Imports
12
13
```typescript
14
import { Client, createClient, gql, cacheExchange, fetchExchange } from "@urql/core";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { Client, createClient, gql, cacheExchange, fetchExchange } = require("@urql/core");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { createClient, gql, cacheExchange, fetchExchange } from "@urql/core";
27
28
// Create a client
29
const client = createClient({
30
url: "https://api.example.com/graphql",
31
exchanges: [cacheExchange, fetchExchange],
32
});
33
34
// Define a query
35
const GetUserQuery = gql`
36
query GetUser($id: ID!) {
37
user(id: $id) {
38
id
39
name
40
41
}
42
}
43
`;
44
45
// Execute query
46
const result = await client.query(GetUserQuery, { id: "123" }).toPromise();
47
48
if (result.error) {
49
console.error("GraphQL Error:", result.error);
50
} else {
51
console.log("User data:", result.data.user);
52
}
53
```
54
55
## Architecture
56
57
@urql/core is built around several key architectural components:
58
59
- **Client**: Central hub managing GraphQL operations and their state
60
- **Exchange System**: Modular pipeline for processing operations (caching, fetching, debugging, etc.)
61
- **Operation Flow**: Request/response cycle using Wonka streams for reactive programming
62
- **Type Safety**: Full TypeScript integration with strongly typed GraphQL operations
63
- **Framework Agnostic**: Core functionality independent of any specific UI framework
64
65
## Capabilities
66
67
### Client Management
68
69
Core client creation and configuration for managing GraphQL operations and state.
70
71
```typescript { .api }
72
interface ClientOptions {
73
url: string;
74
exchanges: Exchange[];
75
fetchOptions?: RequestInit | (() => RequestInit);
76
fetch?: typeof fetch;
77
fetchSubscriptions?: boolean;
78
suspense?: boolean;
79
requestPolicy?: RequestPolicy;
80
preferGetMethod?: boolean | 'force' | 'within-url-limit';
81
}
82
83
function createClient(options: ClientOptions): Client;
84
```
85
86
[Client Management](./client.md)
87
88
### GraphQL Operations
89
90
Execute queries, mutations, and subscriptions with full type safety and reactive streams.
91
92
```typescript { .api }
93
class Client {
94
query<Data = any, Variables extends AnyVariables = AnyVariables>(
95
query: DocumentInput<Data, Variables>,
96
variables: Variables,
97
context?: Partial<OperationContext>
98
): OperationResultSource<OperationResult<Data, Variables>>;
99
100
mutation<Data = any, Variables extends AnyVariables = AnyVariables>(
101
query: DocumentInput<Data, Variables>,
102
variables: Variables,
103
context?: Partial<OperationContext>
104
): OperationResultSource<OperationResult<Data, Variables>>;
105
106
subscription<Data = any, Variables extends AnyVariables = AnyVariables>(
107
query: DocumentInput<Data, Variables>,
108
variables: Variables,
109
context?: Partial<OperationContext>
110
): OperationResultSource<OperationResult<Data, Variables>>;
111
}
112
```
113
114
[GraphQL Operations](./operations.md)
115
116
### Exchange System
117
118
Modular pipeline system for handling caching, fetching, debugging, and custom operation processing.
119
120
```typescript { .api }
121
type Exchange = (input: ExchangeInput) => ExchangeIO;
122
type ExchangeIO = (ops$: Source<Operation>) => Source<OperationResult>;
123
124
function cacheExchange(): Exchange;
125
function fetchExchange(): Exchange;
126
function debugExchange(): Exchange;
127
function subscriptionExchange(options: SubscriptionExchangeOpts): Exchange;
128
function ssrExchange(params: SSRExchangeParams): SSRExchange;
129
function composeExchanges(exchanges: Exchange[]): Exchange;
130
```
131
132
[Exchange System](./exchanges.md)
133
134
### GraphQL Parsing and Utilities
135
136
GraphQL document parsing, request creation, utility functions for operation processing, and internal HTTP transport utilities.
137
138
```typescript { .api }
139
function gql<Data = any, Variables extends AnyVariables = AnyVariables>(
140
strings: TemplateStringsArray,
141
...interpolations: Array<TypedDocumentNode | DocumentNode | string>
142
): TypedDocumentNode<Data, Variables>;
143
144
function createRequest<Data = any, Variables extends AnyVariables = AnyVariables>(
145
query: DocumentInput<Data, Variables>,
146
variables: Variables
147
): GraphQLRequest<Data, Variables>;
148
149
function makeOperation<Data = any, Variables extends AnyVariables = AnyVariables>(
150
kind: OperationType,
151
request: GraphQLRequest<Data, Variables>,
152
context: OperationContext
153
): Operation<Data, Variables>;
154
```
155
156
[Utilities and Parsing](./utilities.md)
157
158
### Error Handling
159
160
Comprehensive error handling for GraphQL and network errors with detailed error information.
161
162
```typescript { .api }
163
class CombinedError extends Error {
164
constructor(params: {
165
networkError?: Error;
166
graphQLErrors?: readonly GraphQLError[];
167
response?: Response;
168
});
169
networkError?: Error;
170
graphQLErrors: GraphQLError[];
171
response?: Response;
172
}
173
174
function makeErrorResult<Data = any, Variables extends AnyVariables = AnyVariables>(
175
operation: Operation<Data, Variables>,
176
error: Error | CombinedError,
177
response?: ExecutionResult
178
): OperationResult<Data, Variables>;
179
```
180
181
[Error Handling](./errors.md)
182
183
### Internal APIs (Advanced)
184
185
Low-level HTTP transport utilities for custom exchange development and advanced use cases.
186
187
```typescript { .api }
188
function makeFetchBody<Data = any, Variables extends AnyVariables = AnyVariables>(
189
request: Omit<GraphQLRequest<Data, Variables>, 'key'>
190
): FetchBody;
191
192
function makeFetchURL(operation: Operation, body?: FetchBody): string;
193
194
function makeFetchOptions(operation: Operation, body?: FetchBody): RequestInit;
195
196
function makeFetchSource(
197
operation: Operation,
198
url: string,
199
fetchOptions: RequestInit
200
): Source<OperationResult>;
201
```
202
203
[Internal APIs](./internal.md)
204
205
## Types
206
207
### Core Operation Types
208
209
```typescript { .api }
210
type OperationType = 'subscription' | 'query' | 'mutation' | 'teardown';
211
212
type RequestPolicy =
213
| 'cache-first'
214
| 'cache-and-network'
215
| 'network-only'
216
| 'cache-only';
217
218
type AnyVariables = { [prop: string]: any } | void | undefined;
219
220
type DocumentInput<Result = { [key: string]: any }, Variables = { [key: string]: any }> =
221
string | DocumentNode | TypedDocumentNode<Result, Variables>;
222
```
223
224
### Request and Result Types
225
226
```typescript { .api }
227
interface GraphQLRequest<Data = any, Variables extends AnyVariables = AnyVariables> {
228
key: number;
229
query: DocumentNode | PersistedDocument | TypedDocumentNode<Data, Variables>;
230
variables: Variables;
231
extensions?: RequestExtensions | undefined;
232
}
233
234
interface OperationResult<Data = any, Variables extends AnyVariables = AnyVariables> {
235
operation: Operation<Data, Variables>;
236
data?: Data;
237
error?: CombinedError;
238
extensions?: Record<string, any>;
239
stale: boolean;
240
hasNext: boolean;
241
}
242
```
243
244
### Context and Configuration Types
245
246
```typescript { .api }
247
interface OperationContext {
248
url: string;
249
fetchOptions?: RequestInit | (() => RequestInit);
250
fetch?: typeof fetch;
251
fetchSubscriptions?: boolean;
252
requestPolicy: RequestPolicy;
253
preferGetMethod?: boolean | 'force' | 'within-url-limit';
254
suspense?: boolean;
255
additionalTypenames?: string[];
256
meta?: OperationDebugMeta;
257
[key: string]: any;
258
}
259
260
interface Operation<Data = any, Variables extends AnyVariables = AnyVariables>
261
extends GraphQLRequest<Data, Variables> {
262
readonly kind: OperationType;
263
context: OperationContext;
264
}
265
```
266
267
### Advanced Types
268
269
```typescript { .api }
270
type OperationResultSource<T extends OperationResult> = Source<T> &
271
PromiseLike<T> & {
272
toPromise(): Promise<T>;
273
subscribe(onResult: (value: T) => void): Subscription;
274
};
275
276
interface ExecutionResult<Data = any> {
277
data?: Data;
278
errors?: GraphQLError[];
279
extensions?: Record<string, any>;
280
incremental?: IncrementalPayload[];
281
pending?: { id: string; path: Array<string | number> }[];
282
}
283
284
interface IncrementalPayload {
285
id?: string;
286
subPath?: Array<string | number>;
287
path?: Array<string | number>;
288
data?: any;
289
errors?: GraphQLError[];
290
extensions?: Record<string, any>;
291
}
292
293
interface PersistedDocument {
294
documentId: string;
295
definitions?: DefinitionNode[];
296
}
297
298
type FileMap = Map<string, File | Blob>;
299
300
interface FetchBody {
301
query?: string;
302
documentId?: string;
303
operationName: string | undefined;
304
variables: undefined | Record<string, any>;
305
extensions: undefined | Record<string, any>;
306
}
307
```