npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@pawells/graphql-codegen-ts

v2.1.1

Published

graphql-codegen plugin generating typed Apollo Client classes for Node.js/TypeScript

Downloads

863

Readme

GraphQL Codegen — TypeScript

GitHub Release CI npm version Node License: MIT GitHub Sponsors

Installation

yarn add -D @pawells/graphql-codegen-ts
npm install --save-dev @pawells/graphql-codegen-ts

Requirements

Peer dependencies that must be present in your project:

  • @apollo/client >=4.0.0
  • @graphql-codegen/typed-document-node >=5.0.0
  • @graphql-codegen/typescript >=4.0.0
  • @graphql-codegen/typescript-apollo-client-helpers >=3.0.0
  • @graphql-codegen/typescript-operations >=4.0.0
  • graphql >=16.0.0
  • rxjs >=7.0.0

This plugin requires four co-plugins to be configured in your codegen.ts: typescript, typescript-operations, typed-document-node, and typescript-apollo-client-helpers. If any are missing, codegen will throw an error listing all required plugins.

This plugin targets Apollo Client 4.x.

Quick Start

Install the required co-plugins alongside this one:

yarn add -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typed-document-node @graphql-codegen/typescript-apollo-client-helpers

Then create a codegen.ts at the root of your project:

import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: 'schema.graphql',
  documents: 'src/**/*.graphql',
  generates: {
    'src/generated/graphql.ts': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typed-document-node',
        'typescript-apollo-client-helpers',
        '@pawells/graphql-codegen-ts',
      ],
    },
  },
};

export default config;

Run codegen to generate the output file:

yarn graphql-codegen

Configuration

IRawPluginConfig is currently an empty interface — the plugin has no configuration options at this time but is designed for extensibility in future releases.

API

GraphQLClient Class

A pre-configured Apollo Client wrapper used in the generated output. It can also be instantiated directly when you need full control over the connection.

new GraphQLClient(options: IGraphQLClientOptions)

IGraphQLClientOptions fields:

| Field | Type | Required | Description | |---|---|---|---| | Name | string | yes | Client label for identification | | HTTP_URI | string | yes | HTTP endpoint URI | | WS_URI | string | yes | WebSocket endpoint URI | | Token | string | no | Static bearer token; use when the token is fixed for the lifetime of the client | | TokenFunction | () => Promise<string> | no | Async function returning a bearer token; use when the token changes per request | | UseTokenFunction | boolean | no | When true, calls TokenFunction() for each request instead of using Token | | LogGraphQLErrors | boolean | no | Logs GraphQL errors to console.error | | LogNetworkErrors | boolean | no | Logs network errors to console.error |

Public members:

  • Apollo: ApolloClient<NormalizedCacheObject> — the underlying Apollo Client instance
  • Name: string, HTTP_URI: string, WS_URI: string — the values supplied in the constructor options
  • Reset(): void — calls apollo.resetStore() then apollo.stop(); errors are silently ignored
  • OnConnecting, OnOpened, OnConnected, OnClosed, OnError — event accessors returning typed event objects from strongly-typed-events

Connection behavior:

  • HTTP and WebSocket operations are split via an Apollo split link
  • Auth link injects the bearer token from Token or TokenFunction() on every request
  • Automatic retries on network errors: up to 10 attempts, initial delay 1 s, max 10 s, with jitter; GraphQL errors are not retried
  • WebSocket includes a ping/pong heartbeat; the connection is closed with code 4408 if no pong is received within 5 seconds
  • All operations default to fetchPolicy: 'no-cache'

Generated Classes

The plugin generates four classes in the output file.

ApolloQueries — one async method per query operation:

public async GetUsers(variables?: GetUsersQueryVariables): Promise<ApolloQueryResult<GetUsersQuery>>

Throws if result.errors is present on the response.

ApolloMutations — one async method per mutation operation:

public async CreateUser(variables: CreateUserMutationVariables): Promise<FetchResult<CreateUserMutation>>

Throws on errors.

ApolloSubscriptions — one async method per subscription operation:

public async OnUserCreated(
  variables?: OnUserCreatedSubscriptionVariables,
  handler: OnUserCreatedEventHandler,
): Promise<ZenObservable.Subscription>

ApolloWrapper — the main entry point that composes the three classes above:

export class ApolloWrapper {
  Handle: GraphQLClient;
  Queries: ApolloQueries;
  Mutations: ApolloMutations;
  Subscriptions: ApolloSubscriptions;
  get Apollo(): ApolloClient<NormalizedCacheObject>;
  constructor(options: GraphQLClientOptions)
}

Variables Optionality Rule

A variables parameter on a generated method is required only when at least one variable in the operation has a NonNullType definition (written as $id: ID! in the schema). If all variables are nullable or the operation defines no variables, the parameter is optional.

# variables is required — $id is non-null
query GetUser($id: ID!) { ... }

# variables is optional — $filter is nullable
query ListUsers($filter: UserFilter) { ... }

# variables is omitted entirely — no variables defined
query GetCurrentUser { ... }

Usage Example

import { ApolloWrapper } from './generated/graphql';

async function main() {
  const client = new ApolloWrapper({
    Name: 'api-client',
    HTTP_URI: 'https://api.example.com/graphql',
    WS_URI: 'wss://api.example.com/graphql',
    Token: process.env.API_TOKEN,
    LogGraphQLErrors: true,
  });

  // Execute a query
  const users = await client.Queries.GetUsers();
  console.log(users.data);

  // Execute a mutation
  const result = await client.Mutations.CreateUser({ name: 'Alice' });

  // Subscribe to events
  const subscription = await client.Subscriptions.OnUserCreated(
    {},
    (result) => {
      console.log('New user:', result.data);
    },
  );

  // Cleanup
  client.Handle.Reset();
}

main().catch(console.error);

Deprecated Exports

GraphQLClientOptions

The GraphQLClientOptions type alias is deprecated. It is still exported for backward compatibility but will be removed in a future major version.

// Deprecated — do not use in new code
import type { GraphQLClientOptions } from '@pawells/graphql-codegen-ts';

// Use this instead
import type { IGraphQLClientOptions } from '@pawells/graphql-codegen-ts';

GraphQLClientOptions is identical to IGraphQLClientOptions. Replace any existing usages with IGraphQLClientOptions directly.

TGraphQLClientOptions

TGraphQLClientOptions is a type alias for IGraphQLClientOptions exported under the T-prefixed naming convention used elsewhere in the monorepo. It is not deprecated and can be used interchangeably with IGraphQLClientOptions.

The ApolloWrapper constructor signature shown elsewhere in this README accepts GraphQLClientOptions — this is the deprecated alias. Prefer IGraphQLClientOptions in new code:

// Preferred
const client = new ApolloWrapper({} as IGraphQLClientOptions);

Known Limitations

IsBrowser Option

The IsBrowser option in IGraphQLClientOptions is deprecated and currently unused. It was intended for runtime environment detection to conditionally enable browser-specific features (such as automatic cookie handling or localStorage integration).

new GraphQLClient({
  Name: 'my-client',
  HTTP_URI: 'http://localhost:4000/graphql',
  WS_URI: 'ws://localhost:4000/graphql',
  IsBrowser: true, // Currently ignored, but accepted
});

Status: Reserved for future use. This option will be implemented in a future release to enable environment-specific behavior. For now, it has no effect and can be safely omitted.

Related Packages

  • @pawells/graphql-codegen-react — The React equivalent of this plugin. Generates typed Apollo Client hooks for React applications instead of class wrappers.
  • @pawells/react-graphql — React runtime companion providing Apollo Client setup, connection state management, and GraphQLProvider.
  • @pawells/graphql-common — Shared GraphQL primitive types and utilities consumed by the generated output.
  • @pawells/nx-graphql — NX executors and builders for running GraphQL codegen as part of an NX pipeline.
  • @pawells/nestjs-graphql — Server-side NestJS module providing Apollo Server integration, guards, interceptors, and DataLoaders.

License

MIT