@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 AsyncDisposable for proper cleanup
  • Template Literals: Re-exports outdent for 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
PackageDescription
`@probitas/client`Core utilities and types
`@probitas/client-http`HTTP client

Installation

deno add jsr:@probitas/client-graphql

Classes

class

#GraphqlExecutionError

class GraphqlExecutionError extends ClientError

Error 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.).

NameDescription
name
kind
errorsGraphQL errors from response
Constructor
new GraphqlExecutionError(
  errors: readonly GraphqlErrorItem[],
  options?: ErrorOptions,
)
Properties
  • readonlynamestring
  • readonlykind"graphql"
  • readonlyerrorsreadonly GraphqlErrorItem[]

    GraphQL errors from response

class

#GraphqlNetworkError

class GraphqlNetworkError extends ClientError

Error 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.).

NameDescription
name
kind
Constructor
new GraphqlNetworkError(message: string, options?: ErrorOptions)
Properties
  • readonlynamestring
  • readonlykind"network"

Interfaces

interface

#GraphqlClient

interface GraphqlClient extends AsyncDisposable

GraphQL client interface.

NameDescription
configClient 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
Methods
query<TData = any, TVariables = Record<string, any>>(
  query: string,
  variables?: TVariables,
  options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>>

Execute a GraphQL query

Parameters
mutation<TData = any, TVariables = Record<string, any>>(
  mutation: string,
  variables?: TVariables,
  options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>>

Execute a GraphQL mutation

Parameters
execute<TData = any, TVariables = Record<string, any>>(
  document: string,
  variables?: TVariables,
  options?: GraphqlOptions,
): Promise<GraphqlResponse<TData>>

Execute a GraphQL document (query or mutation)

Parameters
subscribe<TData = any, TVariables = Record<string, any>>(
  document: string,
  variables?: TVariables,
  options?: GraphqlOptions,
): AsyncIterable<GraphqlResponse<TData>>

Subscribe to a GraphQL subscription via WebSocket

Parameters
close(): Promise<void>

Close the client and release resources

interface

#GraphqlClientConfig

interface GraphqlClientConfig extends CommonOptions

GraphQL client configuration.

NameDescription
urlGraphQL endpoint URL.
headersDefault headers for all requests
wsEndpointWebSocket endpoint URL (for subscriptions)
fetchCustom fetch implementation (for testing/mocking)
throwOnErrorWhether to throw GraphqlError when response contains errors or request fails.
Properties
  • readonlyurlstring | GraphqlConnectionConfig

    GraphQL endpoint URL.

    Can be a URL string or a connection configuration object.

  • readonlyheaders?HeadersInit

    Default headers for all requests

  • readonlywsEndpoint?string

    WebSocket endpoint URL (for subscriptions)

  • readonlyfetch?fetch

    Custom fetch implementation (for testing/mocking)

  • readonlythrowOnError?boolean

    Whether to throw GraphqlError when response contains errors or request fails. Can be overridden per-request via GraphqlOptions.

interface

#GraphqlConnectionConfig

interface GraphqlConnectionConfig extends CommonConnectionConfig

GraphQL connection configuration.

Extends CommonConnectionConfig with GraphQL-specific options.

NameDescription
protocolProtocol to use.
pathGraphQL endpoint path.
Properties
  • readonlyprotocol?"http" | "https"

    Protocol to use.

  • readonlypath?string

    GraphQL endpoint path.

interface

#GraphqlErrorItem

interface GraphqlErrorItem

GraphQL error item as per GraphQL specification.

NameDescription
messageError message
locationsLocation(s) in the GraphQL document where the error occurred
pathPath to the field that caused the error
extensionsAdditional error metadata
Properties
  • readonlymessagestring

    Error message

  • readonlylocationsreadonly { line: number; column: number }[] | null

    Location(s) in the GraphQL document where the error occurred

  • readonlypathreadonly unknown[] | null

    Path to the field that caused the error

  • readonlyextensionsRecord<string, unknown> | null

    Additional error metadata

interface

#GraphqlOptions

interface GraphqlOptions extends CommonOptions

Options for individual GraphQL requests.

NameDescription
headersAdditional request headers
operationNameOperation name (for documents with multiple operations)
throwOnErrorWhether to throw GraphqlError when response contains errors or request fails.
Properties
  • readonlyheaders?HeadersInit

    Additional request headers

  • readonlyoperationName?string

    Operation name (for documents with multiple operations)

  • readonlythrowOnError?boolean

    Whether to throw GraphqlError when response contains errors or request fails.

interface

#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.

NameDescription
processed
ok
error
statusHTTP status code.
headersHTTP response headers.
extensionsResponse extensions.
rawRaw Web standard Response.
dataResponse data (null if no data, may be partial data with errors).
Properties
  • readonlyprocessedtrue
  • readonlyokfalse
  • readonlystatusnumber

    HTTP status code.

  • readonlyheadersHeaders

    HTTP response headers.

  • readonlyextensionsRecord<string, unknown> | null

    Response extensions.

  • readonlyrawglobalThis.Response

    Raw Web standard Response.

  • readonlydataT | null

    Response data (null if no data, may be partial data with errors).

interface

#GraphqlResponseErrorParams

interface GraphqlResponseErrorParams<T>

Parameters for creating an error GraphqlResponse.

NameDescription
url
data
error
extensions
duration
status
raw
Properties
  • readonlyurlstring
  • readonlydataT | null
  • readonlyextensionsRecord<string, unknown> | null
  • readonlydurationnumber
  • readonlystatusnumber
  • readonlyrawglobalThis.Response
interface

#GraphqlResponseFailure

interface GraphqlResponseFailure<T = any> extends GraphqlResponseBase<T>

Failed GraphQL request (network error, HTTP error, etc.).

The request did not reach GraphQL processing.

NameDescription
processed
ok
error
extensionsResponse extensions (always null for failures).
statusHTTP status code (null for network failures).
headersHTTP response headers (null for failures).
rawNo raw response (request didn't reach server).
dataNo data (request didn't reach server).
Properties
  • readonlyprocessedfalse
  • readonlyokfalse
  • readonlyerrorGraphqlFailureError
  • readonlyextensionsnull

    Response extensions (always null for failures).

  • readonlystatusnull

    HTTP status code (null for network failures).

  • readonlyheadersnull

    HTTP response headers (null for failures).

  • readonlyrawnull

    No raw response (request didn't reach server).

  • readonlydatanull

    No data (request didn't reach server).

interface

#GraphqlResponseFailureParams

interface GraphqlResponseFailureParams

Parameters for creating a failure GraphqlResponse.

NameDescription
url
error
duration
Properties
interface

#GraphqlResponseSuccess

interface GraphqlResponseSuccess<T = any> extends GraphqlResponseBase<T>

Successful GraphQL response (no errors).

NameDescription
processed
ok
error
statusHTTP status code.
headersHTTP response headers.
extensionsResponse extensions.
rawRaw Web standard Response.
dataResponse data (null if no data).
Properties
  • readonlyprocessedtrue
  • readonlyoktrue
  • readonlyerrornull
  • readonlystatusnumber

    HTTP status code.

  • readonlyheadersHeaders

    HTTP response headers.

  • readonlyextensionsRecord<string, unknown> | null

    Response extensions.

  • readonlyrawglobalThis.Response

    Raw Web standard Response.

  • readonlydataT | null

    Response data (null if no data).

interface

#GraphqlResponseSuccessParams

interface GraphqlResponseSuccessParams<T>

Parameters for creating a successful GraphqlResponse.

NameDescription
url
data
extensions
duration
status
raw
Properties
  • readonlyurlstring
  • readonlydataT | null
  • readonlyextensionsRecord<string, unknown> | null
  • readonlydurationnumber
  • readonlystatusnumber
  • readonlyrawglobalThis.Response

Functions

function

#createGraphqlClient

function createGraphqlClient(config: GraphqlClientConfig): GraphqlClient

Create a new GraphQL client instance.

The client provides methods for executing GraphQL queries, mutations, and subscriptions with automatic error handling and response parsing.

Parameters
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

type

#GraphqlFailureError

type GraphqlFailureError = GraphqlNetworkError | AbortError | TimeoutError

Error types that indicate the operation was not processed. These are errors that occur before the request reaches the GraphQL server.

type

#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

const

#outdent

const outdent: Outdent
Search Documentation