Files
web/lib/graphql/batchRequest.ts
2024-08-28 14:55:31 +02:00

36 lines
862 B
TypeScript

import "server-only"
import { request } from "./request"
import type { BatchRequestDocument } from "graphql-request"
import type { Data } from "@/types/request"
export async function batchRequest<T>(
queries: (BatchRequestDocument & { options?: RequestInit })[]
): Promise<Data<T>> {
try {
const response = await Promise.allSettled(
queries.map((query) =>
request<T>(query.document, query.variables, query.options)
)
)
let data = {} as T
const reasons = []
response.forEach((res) => {
if (res.status === "fulfilled") {
data = Object.assign({}, data, res.value.data)
} else {
reasons.push(res.reason)
}
})
return { data }
} catch (error) {
console.error("Error in batched graphql request")
console.error(error)
throw new Error("Something went wrong")
}
}