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.
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;
};
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