Files
web/lib/request.ts
2024-02-07 11:58:54 +01:00

52 lines
1.5 KiB
TypeScript

import "server-only"
import { request as graphqlRequest } from "graphql-request"
import { env } from "@/env/server.mjs"
import type { Data } from "@/types/request"
import type { DocumentNode } from "graphql";
export async function request<T>(query: string | DocumentNode, variables?: {}): Promise<Data<T>> {
try {
if (env.PRINT_QUERY) {
const graphqlRawRequest = (await import("graphql-request")).rawRequest
const print = (await import("graphql/language/printer")).print
const rawResponse = await graphqlRawRequest<T>(
env.CMS_URL,
print(query as DocumentNode),
variables,
{
"access_token": env.CMS_ACCESS_TOKEN,
"Content-Type": "application/json",
}
)
/**
* TODO: Send to Monitoring (Logging and Metrics)
*/
console.log({ complexityLimit: rawResponse.headers.get("x-query-complexity") })
console.log({ referenceDepth: rawResponse.headers.get("x-reference-depth") })
console.log({ resolverCost: rawResponse.headers.get("x-resolver-cost") })
return {
data: rawResponse.data,
}
}
const response = await graphqlRequest<T>({
document: query,
requestHeaders: {
"access_token": env.CMS_ACCESS_TOKEN,
"Content-Type": "application/json",
},
url: env.CMS_URL,
variables,
})
return { data: response }
} catch (error) {
console.error(error)
throw new Error("Something went wrong")
}
}