Introduction

This document discusses the benefits of using GraphQL Code Generator (codegen) with GraphQL-Request in our Next.js 14 project with TypeScript. The aim is to demonstrate how this approach can optimize our development process by providing automatically generated types, reducing errors, and facilitating code maintenance.

Benefits of Codegen

  1. Automation and Productivity:
  2. Reliability:
  3. Maintenance:

Practical Example: Before and After

Before Codegen

  1. Function Creation
const fetchFAQS = async (
  countryCode: CountryCode,
  params?: {
    ids?: string[];
    types?: FAQType;
    relatedCity?: string;
  }
): Promise<FAQT[]> => {
  const query = `query MyQuery($ids: [String],$relatedCity: String, $type_contains_some: [String]) {
      faqCollection(where: {sys: {id_in: $ids}, type_contains_some: $type_contains_some, relatedCity: $relatedCity, country: { code: "${countryCode}" } }, limit: 10) {
          items {
              title
              slug
              type
              country {
                  code
              }
              content {
                  json
                  links {
                      assets {
                          block {
                              sys {
                                  id
                              }
                              title
                              description
                              url
                              width
                              height
                          }
                      }
                  }
              }
          }
      }
  }`;

  const variables = {
    type_contains_some: params?.types,
    relatedCity: params?.relatedCity,
    ids: params?.ids,
  };

  const res = await fetch(apiUrl, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({ query, variables }),
  });

  if (!res.ok) {
    throw new Error("Failed to fetch FAQS");
  }
  const { data } = await res.json();

  const faq = data.faqCollection.items;

  return faq;
};

  1. Creating Types
const FAQSchema = z.object({
  title: z.string(),
  slug: z.string(),
  type: faqTypes,
  country: CountrySchema,
  content: z.any(),
  isEducationalGuide: z.boolean(),
  relatedCity: z.string().nullish(),
});


After Codegen

  1. Configuration of Codegen