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.
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();
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.');
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');