@unifiedsoftware/graphql-client
v1.0.2
Published
Flexible GraphQL client with event system, interceptors, and caching
Downloads
263
Keywords
Readme
@unifiedsoftware/graphql-client
Flexible GraphQL client with event system, interceptors, and caching built on top of @unifiedsoftware/http-client.
Features
- Built on HttpClient - Leverages the flexible HTTP client with interceptors and event system
- Query Caching - Optional in-memory caching with configurable TTL
- Type-Safe - Full TypeScript support with generic types
- Error Handling - Comprehensive GraphQL error handling
- Lightweight - Minimal dependencies, focused on core functionality
Installation
pnpm add @unifiedsoftware/graphql-client @unifiedsoftware/http-clientQuick Start
import { HttpClient, createFetchAdapter } from "@unifiedsoftware/http-client";
import { createGraphQLClient } from "@unifiedsoftware/graphql-client";
// Create HTTP client
const httpClient = new HttpClient({
adapter: createFetchAdapter(),
baseURL: "https://api.example.com",
headers: {
Authorization: "Bearer your-token",
},
});
// Create GraphQL client
const graphql = createGraphQLClient(httpClient, {
endpoint: "/graphql",
cache: true,
cacheTTL: 5 * 60 * 1000, // 5 minutes
});
// Execute a query
const data = await graphql.query(
`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`,
{ id: "123" }
);
console.log(data.user);Usage
Queries
// Simple query
const data = await graphql.query(`
query {
users {
id
name
}
}
`);
// Query with variables
const data = await graphql.query(
`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`,
{ id: "123" }
);
// Query with operation name
const data = await graphql.query(
`query GetUser($id: ID!) { ... }`,
{ id: "123" },
"GetUser"
);Mutations
// Execute a mutation
const result = await graphql.mutate(
`
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) {
id
name
email
}
}
`,
{
input: {
name: "John Doe",
email: "[email protected]",
},
}
);
console.log(result.createUser);Type Safety
// Define your types
interface User {
id: string;
name: string;
email: string;
}
interface GetUserResponse {
user: User;
}
// Use with type parameter
const data = await graphql.query<GetUserResponse>(
`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`,
{ id: "123" }
);
// TypeScript knows the shape of data
console.log(data.user.name); // ✓ Type-safeError Handling
import { GraphQLError } from "@unifiedsoftware/graphql-client";
try {
const data = await graphql.query(`...`);
} catch (error) {
if (error instanceof GraphQLError) {
console.error("GraphQL Errors:");
error.messages.forEach((msg) => console.error(` - ${msg}`));
// Access detailed error information
console.error("First error:", error.firstError);
console.error("All errors:", error.errors);
}
}Caching
// Enable caching
const graphql = createGraphQLClient(httpClient, {
endpoint: "/graphql",
cache: true,
cacheTTL: 5 * 60 * 1000, // 5 minutes
});
// First call - fetches from server
const data1 = await graphql.query(`query { users { id } }`);
// Second call - returns from cache
const data2 = await graphql.query(`query { users { id } }`);
// Clear specific query cache
graphql.clearCache(`query { users { id } }`);
// Clear all cache
graphql.clearCache();Custom Headers
const graphql = createGraphQLClient(httpClient, {
endpoint: "/graphql",
headers: {
"X-Custom-Header": "value",
Authorization: "Bearer token",
},
});Raw Requests
// Execute a raw GraphQL request
const response = await graphql.request({
query: `query { users { id } }`,
variables: { id: "123" },
operationName: "GetUsers",
});
// Access full response including errors
console.log(response.data);
console.log(response.errors);
console.log(response.extensions);API Reference
createGraphQLClient(httpClient, config)
Creates a new GraphQL client instance.
Parameters:
httpClient: HttpClient- Instance of@unifiedsoftware/http-clientconfig: GraphQLClientConfig- Configuration options
Returns: GraphQLClient
GraphQLClientConfig
interface GraphQLClientConfig {
endpoint: string; // GraphQL endpoint URL
headers?: Record<string, string>; // Default headers
cache?: boolean; // Enable caching (default: false)
cacheTTL?: number; // Cache TTL in ms (default: 5 minutes)
}GraphQLClient
query<T>(query, variables?, operationName?): Promise<T>
Execute a GraphQL query.
mutate<T>(mutation, variables?, operationName?): Promise<T>
Execute a GraphQL mutation.
request<T>(request): Promise<GraphQLResponse<T>>
Execute a raw GraphQL request.
clearCache(query?, variables?): void
Clear cache entries.
getHttpClient(): HttpClient
Get the underlying HTTP client instance.
Integration with Generated Clients
This package is designed to work seamlessly with clients generated by @unifiedsoftware/generator-graphql:
import { createGraphQLClient } from "@unifiedsoftware/graphql-client";
import { createPortalApiClient } from "./generated/portal-api";
const httpClient = new HttpClient({
/* ... */
});
const graphql = createGraphQLClient(httpClient, {
endpoint: "https://localhost:44357/graphql",
});
const client = createPortalApiClient(graphql);
// Use typed operations
const users = await client.queries.getUsers();
const user = await client.mutations.createUser({ name: "John" });License
MIT
