Files
web/packages/trpc/lib/graphql/batchRequest.ts
Rasmus Langvad c65091b36a Merged in feat/SW-3644-storybook-v10 (pull request #3240)
feat(SW-3644): Storybook v10

* Auto update to Storybook v10

* Add scandic theme and logo

* Update yarn.lock

* Update formatting of package.json

* Update vitest config and playwright plugin

* Remove vitest 4 update

* Re-added comment

* Update the Typography component to explicitly return React.ReactNode

* Add an explicit type assertion to the export

* Add an explicit type assertion to the export for Checkbox

* Explicit return type assertion

* Add an explicit type assertion to the export

* Update @types/react and fix ts warnings

* Updated typings


Approved-by: Linus Flood
Approved-by: Matilda Landström
2025-11-28 08:05:40 +00:00

77 lines
1.9 KiB
TypeScript

import "server-only"
import deepmerge from "deepmerge"
import merge from "deepmerge"
import type { DocumentNode } from "graphql"
import { createLogger } from "@scandic-hotels/common/logger/createLogger"
import { request } from "./request"
import type { CacheTime } from "@scandic-hotels/common/dataCache"
import type { BatchRequestDocument } from "graphql-request"
import type { Data } from "../types/requestData"
export async function batchRequest<T>(
queries: (BatchRequestDocument & {
cacheOptions?: {
key: string | string[]
ttl: CacheTime
}
})[]
): Promise<Data<T>> {
const batchLogger = createLogger("graphql-batch-request")
try {
const response = await Promise.allSettled(
queries.map((query) =>
request<T>(
query.document as string | DocumentNode,
query.variables,
query.cacheOptions
)
)
)
let data = {} as T
const reasons: PromiseRejectedResult["reason"][] = []
response.forEach((res) => {
if (res.status === "fulfilled") {
data = deepmerge(data, res.value.data, { arrayMerge })
} else {
reasons.push(res.reason)
}
})
if (reasons.length) {
reasons.forEach((reason) => {
batchLogger.error(`Batch request failed`, reason)
})
}
return { data }
} catch (error) {
batchLogger.error("Error in batched graphql request", error)
throw error
}
}
function arrayMerge(
target: any[],
source: any[],
options: merge.ArrayMergeOptions
) {
const destination = target.slice()
source.forEach((item, index) => {
if (typeof destination[index] === "undefined") {
destination[index] = options.cloneUnlessOtherwiseSpecified(item, options)
} else if (options?.isMergeableObject(item)) {
destination[index] = merge(target[index], item, options)
} else if (target.indexOf(item) === -1) {
destination.push(item)
}
})
return destination
}