Build Typed GraphQL Queries

3.1.6 · active · verified Tue Apr 21

typed-graphqlify is a TypeScript library designed to streamline the process of building GraphQL queries by providing a single source of truth for both the GraphQL query structure and its corresponding TypeScript types. It eliminates the common problem of redundancy found in many GraphQL client setups where developers must define a GraphQL query string and then separately define a matching TypeScript interface. The library, currently at version 3.1.6, generally sees minor updates every few weeks to months, focusing on dependency updates and minor feature enhancements. Its core differentiator lies in its ability to generate GraphQL query strings and strong TypeScript types directly from a GraphQL-like JavaScript object structure, using dedicated `types` helpers for scalar and optional fields. It primarily acts as a query builder, providing the necessary string for execution, but does not handle the network request itself, integrating seamlessly with existing GraphQL clients like Apollo or Relay for actual data fetching.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a typed GraphQL query, generate its string representation, and type-safely consume its result.

import { query, types } from 'typed-graphqlify';

// Mock an execution function for demonstration purposes
async function executeGraphql<T>(graphqlQuery: string): Promise<T> {
  console.log('Executing GraphQL query:\n', graphqlQuery);
  // In a real application, this would make an actual network request
  // to your GraphQL endpoint (e.g., using fetch, axios, or a GraphQL client).
  // For this example, we'll return a mock data structure that matches the
  // query's expected type, simulating a successful response.
  return Promise.resolve({
    user: {
      id: 123,
      name: 'John Doe',
      bankAccount: {
        id: 456,
        branch: 'Main Branch', // Or undefined if optional and not present
      },
    },
  } as T);
}

// Define a GraphQL query using typed-graphqlify's DSL
const getUserQuery = query('GetUser', {
  user: {
    id: types.number,
    name: types.string,
    bankAccount: {
      id: types.number,
      branch: types.optional.string, // Define 'branch' as an optional string
    },
  },
});

console.log('Generated GraphQL Query:\n', getUserQuery.toString());

// Execute the GraphQL query and infer the result type safely
const data: typeof getUserQuery.data = await executeGraphql(getUserQuery.toString());

console.log('Received data:', data);
// Demonstrate type-safety: 'data' is strongly typed based on the query definition
console.log(`User ID: ${data.user.id}`);
console.log(`User Name: ${data.user.name}`);
if (data.user.bankAccount.branch) {
  console.log(`Bank Branch: ${data.user.bankAccount.branch}`);
} else {
  console.log('Bank Branch: Not provided');
}

view raw JSON →