@probitas/client-graphql
GraphQL client for Probitas scenario testing framework.
This package provides a GraphQL client designed for integration testing of GraphQL APIs.
Features
- Query & Mutation: Full support for GraphQL operations
- Variables Support: Pass typed variables to queries and mutations
- Duration Tracking: Built-in timing for performance monitoring
- Error Inspection: Inspect GraphQL errors and their structure
- Resource Management: Implements
AsyncDisposablefor proper cleanup - Template Literals: Re-exports
outdentfor clean multi-line queries
Installation
deno add jsr:@probitas/client-graphql
Quick Start
import { createGraphqlClient, outdent } from "@probitas/client-graphql";
const client = createGraphqlClient({ url: "http://localhost:4000/graphql" });
// Query with variables
const res = await client.query(outdent`
query GetUser($id: ID!) {
user(id: $id) { id name email }
}
`, { id: "123" });
console.log("User:", res.data);
// Mutation
const created = await client.mutation(outdent`
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) { id name }
}
`, { input: { name: "Jane", email: "jane@example.com" } });
console.log("Created:", created.data);
await client.close();
Using with using Statement
import { createGraphqlClient } from "@probitas/client-graphql";
await using client = createGraphqlClient({ url: "http://localhost:4000/graphql" });
const res = await client.query(`{ __typename }`);
console.log(res.data);
// Client automatically closed when block exits
Related Packages
| Package | Description |
|---|---|
| `@probitas/client` | Core utilities and types |
| `@probitas/client-http` | HTTP client |
Links
Installation
deno add jsr:@probitas/client-graphqlClasses
#GraphqlExecutionError
class GraphqlExecutionError extends ClientErrorClientErrorError thrown for GraphQL execution errors.
This error is returned when the GraphQL server processes the request but returns errors in the response (validation errors, resolver errors, etc.).
Constructor
new GraphqlExecutionError(
errors: readonly GraphqlErrorItem[],
options?: ErrorOptions,
)Properties
- readonly
namestring - readonly
kind"graphql" GraphQL errors from response
#GraphqlNetworkError
class GraphqlNetworkError extends ClientErrorClientErrorError thrown for network-level failures.
This error indicates that the request could not reach or be processed by the GraphQL server (connection refused, HTTP errors, etc.).
Constructor
new GraphqlNetworkError(message: string, options?: ErrorOptions)Properties
- readonly
namestring - readonly
kind"network"
Interfaces
#GraphqlClient
interface GraphqlClient extends AsyncDisposableGraphQL client interface.
| Name | Description |
|---|---|
config | Client configuration |
query() | Execute a GraphQL query |
mutation() | Execute a GraphQL mutation |
execute() | Execute a GraphQL document (query or mutation) |
subscribe() | Subscribe to a GraphQL subscription via WebSocket |
close() | Close the client and release resources |
Properties
Client configuration
Methods
query<TData = any, TVariables = Record<string, any>>(
query: string,
variables?: TVariables,
options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>>Execute a GraphQL query
Parameters
querystringvariables?TVariablesoptions?GraphqlOptions
mutation<TData = any, TVariables = Record<string, any>>(
mutation: string,
variables?: TVariables,
options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>>Execute a GraphQL mutation
Parameters
mutationstringvariables?TVariablesoptions?GraphqlOptions
execute<TData = any, TVariables = Record<string, any>>(
document: string,
variables?: TVariables,
options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>>Execute a GraphQL document (query or mutation)
Parameters
documentstringvariables?TVariablesoptions?GraphqlOptions
subscribe<TData = any, TVariables = Record<string, any>>(
document: string,
variables?: TVariables,
options?: GraphqlOptions,
): AsyncIterable<GraphqlResponse<TData>>Subscribe to a GraphQL subscription via WebSocket
Parameters
documentstringvariables?TVariablesoptions?GraphqlOptions
close(): Promise<void>Close the client and release resources
#GraphqlClientConfig
interface GraphqlClientConfig extends CommonOptionsGraphQL client configuration.
| Name | Description |
|---|---|
url | GraphQL endpoint URL. |
headers | Default headers for all requests |
wsEndpoint | WebSocket endpoint URL (for subscriptions) |
fetch | Custom fetch implementation (for testing/mocking) |
throwOnError | Whether to throw GraphqlError when response contains errors or request fails. |
Properties
GraphQL endpoint URL.
Can be a URL string or a connection configuration object.
- readonly
headers?HeadersInitDefault headers for all requests
- readonly
wsEndpoint?stringWebSocket endpoint URL (for subscriptions)
- readonly
fetch?fetchCustom fetch implementation (for testing/mocking)
- readonly
throwOnError?booleanWhether to throw GraphqlError when response contains errors or request fails. Can be overridden per-request via GraphqlOptions.
#GraphqlConnectionConfig
interface GraphqlConnectionConfig extends CommonConnectionConfigGraphQL connection configuration.
Extends CommonConnectionConfig with GraphQL-specific options.
Properties
- readonly
protocol?"http" | "https"Protocol to use.
- readonly
path?stringGraphQL endpoint path.
#GraphqlErrorItem
interface GraphqlErrorItemGraphQL error item as per GraphQL specification.
| Name | Description |
|---|---|
message | Error message |
locations | Location(s) in the GraphQL document where the error occurred |
path | Path to the field that caused the error |
extensions | Additional error metadata |
Properties
- readonly
messagestringError message
- readonly
locationsreadonly { line: number; column: number }[] | nullLocation(s) in the GraphQL document where the error occurred
- readonly
pathreadonly unknown[] | nullPath to the field that caused the error
- readonly
extensionsRecord<string, unknown> | nullAdditional error metadata
#GraphqlOptions
interface GraphqlOptions extends CommonOptionsOptions for individual GraphQL requests.
| Name | Description |
|---|---|
headers | Additional request headers |
operationName | Operation name (for documents with multiple operations) |
throwOnError | Whether to throw GraphqlError when response contains errors or request fails. |
Properties
- readonly
headers?HeadersInitAdditional request headers
- readonly
operationName?stringOperation name (for documents with multiple operations)
- readonly
throwOnError?booleanWhether to throw GraphqlError when response contains errors or request fails.
#GraphqlResponseError
interface GraphqlResponseError<T = any> extends GraphqlResponseBase<T>GraphQL response with execution errors.
Note: GraphQL allows partial success where both data and errors are present. Use data() to access any partial data.
| Name | Description |
|---|---|
processed | — |
ok | — |
error | — |
status | HTTP status code. |
headers | HTTP response headers. |
extensions | Response extensions. |
raw | Raw Web standard Response. |
data | Response data (null if no data, may be partial data with errors). |
Properties
- readonly
processedtrue - readonly
okfalse - readonly
statusnumberHTTP status code.
- readonly
headersHeadersHTTP response headers.
- readonly
extensionsRecord<string, unknown> | nullResponse extensions.
- readonly
rawglobalThis.ResponseRaw Web standard Response.
- readonly
dataT | nullResponse data (null if no data, may be partial data with errors).
#GraphqlResponseErrorParams
interface GraphqlResponseErrorParams<T>Parameters for creating an error GraphqlResponse.
Properties
- readonly
urlstring - readonly
dataT | null - readonly
extensionsRecord<string, unknown> | null - readonly
durationnumber - readonly
statusnumber - readonly
rawglobalThis.Response
#GraphqlResponseFailure
interface GraphqlResponseFailure<T = any> extends GraphqlResponseBase<T>Failed GraphQL request (network error, HTTP error, etc.).
The request did not reach GraphQL processing.
| Name | Description |
|---|---|
processed | — |
ok | — |
error | — |
extensions | Response extensions (always null for failures). |
status | HTTP status code (null for network failures). |
headers | HTTP response headers (null for failures). |
raw | No raw response (request didn't reach server). |
data | No data (request didn't reach server). |
Properties
- readonly
processedfalse - readonly
okfalse - readonly
extensionsnullResponse extensions (always null for failures).
- readonly
statusnullHTTP status code (null for network failures).
- readonly
headersnullHTTP response headers (null for failures).
- readonly
rawnullNo raw response (request didn't reach server).
- readonly
datanullNo data (request didn't reach server).
#GraphqlResponseFailureParams
interface GraphqlResponseFailureParamsParameters for creating a failure GraphqlResponse.
Properties
- readonly
urlstring - readonly
durationnumber
#GraphqlResponseSuccess
interface GraphqlResponseSuccess<T = any> extends GraphqlResponseBase<T>Successful GraphQL response (no errors).
| Name | Description |
|---|---|
processed | — |
ok | — |
error | — |
status | HTTP status code. |
headers | HTTP response headers. |
extensions | Response extensions. |
raw | Raw Web standard Response. |
data | Response data (null if no data). |
Properties
- readonly
processedtrue - readonly
oktrue - readonly
errornull - readonly
statusnumberHTTP status code.
- readonly
headersHeadersHTTP response headers.
- readonly
extensionsRecord<string, unknown> | nullResponse extensions.
- readonly
rawglobalThis.ResponseRaw Web standard Response.
- readonly
dataT | nullResponse data (null if no data).
#GraphqlResponseSuccessParams
interface GraphqlResponseSuccessParams<T>Parameters for creating a successful GraphqlResponse.
Properties
- readonly
urlstring - readonly
dataT | null - readonly
extensionsRecord<string, unknown> | null - readonly
durationnumber - readonly
statusnumber - readonly
rawglobalThis.Response
Functions
#createGraphqlClient
function createGraphqlClient(config: GraphqlClientConfig): GraphqlClientCreate a new GraphQL client instance.
The client provides methods for executing GraphQL queries, mutations, and subscriptions with automatic error handling and response parsing.
Parameters
configGraphqlClientConfig- Client configuration including URL and default options
Returns
GraphqlClient — A new GraphQL client instance
Examples
Basic query
import { createGraphqlClient } from "@probitas/client-graphql";
const client = createGraphqlClient({
url: "http://localhost:4000/graphql",
});
const response = await client.query(`
query GetUser($id: ID!) {
user(id: $id) { id name email }
}
`, { id: "123" });
console.log(response.data);
await client.close();
Using connection config object
import { createGraphqlClient } from "@probitas/client-graphql";
const client = createGraphqlClient({
url: { host: "api.example.com", port: 443, protocol: "https" },
});
await client.close();
Mutation with error handling
import { createGraphqlClient } from "@probitas/client-graphql";
const client = createGraphqlClient({ url: "http://localhost:4000/graphql" });
const response = await client.mutation(`
mutation CreateUser($input: CreateUserInput!) {
createUser(input: $input) { id }
}
`, { input: { name: "Alice", email: "alice@example.com" } });
if (response.ok) {
console.log("Created user:", (response.data as any).createUser.id);
}
await client.close();
Using await using for automatic cleanup
import { createGraphqlClient } from "@probitas/client-graphql";
await using client = createGraphqlClient({
url: "http://localhost:4000/graphql",
});
const response = await client.query(`{ __typename }`);
// Client automatically closed when scope exits
Types
#GraphqlFailureError
type GraphqlFailureError = GraphqlNetworkError | AbortError | TimeoutErrorError types that indicate the operation was not processed. These are errors that occur before the request reaches the GraphQL server.
#GraphqlResponse
type GraphqlResponse<T = any> = GraphqlResponseSuccess<T> | GraphqlResponseError<T> | GraphqlResponseFailure<T>GraphQL response union type.
Use processed to distinguish between server responses and failures:
processed === true: Server responded (Success or Error)processed === false: Request failed (Failure)
Use ok to check for success:
ok === true: Success (no errors)ok === false: Error or Failure
Variables
#outdent
const outdent: Outdent