GraphQL with TypeScript: Practical Examples

Explore practical examples of using GraphQL with TypeScript for effective API integration.
By Jamie

Introduction to GraphQL with TypeScript

GraphQL is a powerful query language for APIs that allows clients to request exactly the data they need. When combined with TypeScript, developers can leverage type safety, making it easier to manage complex data structures and ensuring better code quality. This article presents three diverse and practical examples of using GraphQL with TypeScript that will help you understand how to implement this technology effectively.

Example 1: Fetching User Data

Use Case

In a web application, you may need to fetch user profiles from a GraphQL API to display them on a dashboard. This example demonstrates how to structure a GraphQL query using TypeScript to retrieve user data.

import { GraphQLClient, gql } from 'graphql-request';

const endpoint = 'https://api.example.com/graphql';
const client = new GraphQLClient(endpoint);

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

async function fetchUsers() {
  try {
    const data = await client.request(GET_USERS);
    console.log(data.users);
  } catch (error) {
    console.error(error);
  }
}

fetchUsers();

Notes

  • Ensure the GraphQL API endpoint is correct.
  • Consider adding error handling to manage different API response scenarios.

Example 2: Creating a New Post

Use Case

In a blogging platform, you may want to allow users to create new posts via a GraphQL mutation. This example shows how to define and execute a mutation using TypeScript.

import { GraphQLClient, gql } from 'graphql-request';

const endpoint = 'https://api.example.com/graphql';
const client = new GraphQLClient(endpoint);

const CREATE_POST = gql`
  mutation CreatePost($title: String!, $content: String!) {
    createPost(title: $title, content: $content) {
      id
      title
      content
    }
  }
`;

async function createNewPost(title: string, content: string) {
  try {
    const variables = { title, content };
    const data = await client.request(CREATE_POST, variables);
    console.log(data.createPost);
  } catch (error) {
    console.error(error);
  }
}

createNewPost('My New Post', 'This is the content of my new post.');

Notes

  • Always validate user input before sending it to the API.
  • You can extend the mutation to include more fields as necessary.

Example 3: Updating User Information

Use Case

In an application that manages user profiles, an update functionality is often required. This example illustrates how to update user information using a GraphQL mutation with TypeScript.

import { GraphQLClient, gql } from 'graphql-request';

const endpoint = 'https://api.example.com/graphql';
const client = new GraphQLClient(endpoint);

const UPDATE_USER = gql`
  mutation UpdateUser($id: ID!, $name: String, $email: String) {
    updateUser(id: $id, name: $name, email: $email) {
      id
      name
      email
    }
  }
`;

async function updateUser(id: string, name?: string, email?: string) {
  try {
    const variables = { id, name, email };
    const data = await client.request(UPDATE_USER, variables);
    console.log(data.updateUser);
  } catch (error) {
    console.error(error);
  }
}

updateUser('1', 'Updated Name', 'updated.email@example.com');

Notes

  • The mutation can be designed to accept optional parameters for a more flexible update.
  • Ensure proper authentication and authorization mechanisms are in place when performing updates.