feat(WEB-103): create request client to be able to use next caching

This commit is contained in:
Simon Emanuelsson
2024-02-20 19:21:50 +01:00
parent 7417abc814
commit d1d20ce555
5 changed files with 31 additions and 17 deletions

View File

@@ -4,10 +4,10 @@ import { request } from "./request"
import type { Data } from "@/types/request"
import type { BatchRequestDocument } from "graphql-request"
export async function batchRequest<T>(queries: BatchRequestDocument[]): Promise<Data<T>> {
export async function batchRequest<T>(queries: (BatchRequestDocument & NextFetchRequestConfig)[]): Promise<Data<T>> {
try {
const response = await Promise.allSettled(
queries.map(query => request<T>(query.document, query.variables))
queries.map(query => request<T>(query.document, query.variables, { tags: query.tags }))
)
let data = {} as T

View File

@@ -1,21 +1,27 @@
import "server-only"
import { request as graphqlRequest } from "graphql-request"
import { GraphQLClient } from "graphql-request"
import { env } from "@/env/server"
import { cache } from "react"
import type { Data } from "@/types/request"
import type { DocumentNode } from "graphql"
export async function request<T>(
query: string | DocumentNode,
variables?: {}
variables?: {},
next?: NextFetchRequestConfig
): Promise<Data<T>> {
try {
if (env.PRINT_QUERY) {
const graphqlRawRequest = (await import("graphql-request")).rawRequest
const print = (await import("graphql/language/printer")).print
const client = new GraphQLClient(env.CMS_URL, {
fetch: cache(async function (url: URL | RequestInfo, params: RequestInit | undefined) {
return fetch(url, params)
}),
next,
})
const rawResponse = await graphqlRawRequest<T>(
env.CMS_URL,
if (env.PRINT_QUERY) {
const print = (await import("graphql/language/printer")).print
const rawResponse = await client.rawRequest<T>(
print(query as DocumentNode),
variables,
{
@@ -40,13 +46,12 @@ export async function request<T>(
}
}
const response = await graphqlRequest<T>({
const response = await client.request<T>({
document: query,
requestHeaders: {
access_token: env.CMS_ACCESS_TOKEN,
"Content-Type": "application/json",
},
url: env.CMS_URL,
variables,
})