Files
web/apps/scandic-web/lib/graphql/_request.ts
Anton Gunnarsson 80100e7631 Merged in monorepo-step-1 (pull request #1080)
Migrate to a monorepo setup - step 1

* Move web to subfolder /apps/scandic-web

* Yarn + transitive deps

- Move to yarn
- design-system package removed for now since yarn doesn't
support the parameter for token (ie project currently broken)
- Add missing transitive dependencies as Yarn otherwise
prevents these imports
- VS Code doesn't pick up TS path aliases unless you open
/apps/scandic-web instead of root (will be fixed with monorepo)

* Pin framer-motion to temporarily fix typing issue

https://github.com/adobe/react-spectrum/issues/7494

* Pin zod to avoid typ error

There seems to have been a breaking change in the types
returned by zod where error is now returned as undefined
instead of missing in the type. We should just handle this
but to avoid merge conflicts just pin the dependency for
now.

* Pin react-intl version

Pin version of react-intl to avoid tiny type issue where formatMessage
does not accept a generic any more. This will be fixed in a future
commit, but to avoid merge conflicts just pin for now.

* Pin typescript version

Temporarily pin version as newer versions as stricter and results in
a type error. Will be fixed in future commit after merge.

* Setup workspaces

* Add design-system as a monorepo package

* Remove unused env var DESIGN_SYSTEM_ACCESS_TOKEN

* Fix husky for monorepo setup

* Update netlify.toml

* Add lint script to root package.json

* Add stub readme

* Fix react-intl formatMessage types

* Test netlify.toml in root

* Remove root toml

* Update netlify.toml publish path

* Remove package-lock.json

* Update build for branch/preview builds


Approved-by: Linus Flood
2025-02-26 10:36:17 +00:00

144 lines
4.0 KiB
TypeScript

import "server-only"
import { ClientError, type GraphQLClient } from "graphql-request"
import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
import type { DocumentNode } from "graphql"
import type { Data } from "@/types/request"
export async function request<T>(
client: GraphQLClient,
query: string | DocumentNode,
variables?: {},
params?: RequestInit
): Promise<Data<T>> {
try {
client.setHeaders({
access_token: env.CMS_ACCESS_TOKEN,
branch: env.CMS_BRANCH,
"Content-Type": "application/json",
...params?.headers,
})
client.requestConfig.cache = params?.cache
client.requestConfig.next = params?.next
if (env.PRINT_QUERY) {
const print = (await import("graphql/language/printer")).print
const rawResponse = await client.rawRequest<T>(
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,
}
}
try {
// @ts-expect-error: query can be undefined (?)
const operationName = (query as DocumentNode).definitions.find(
(d) => d.kind === "OperationDefinition" && d.operation === "query"
// @ts-expect-error: name does not exist (?)
).name.value
console.log(`[gql] Sending graphql request to ${env.CMS_URL}`, {
operationName,
variables,
})
} catch (e) {
console.error(`[gql] Unable to extract operation name from query`, {
query,
error: e,
})
console.log(`[gql] Sending graphql request to ${env.CMS_URL}`, {
operationName: "<Unable to extract>",
variables,
})
}
const response = await client.request<T>({
document: query,
variables,
})
try {
// @ts-expect-error: query can be undefined (?)
const operationName = (query as DocumentNode).definitions.find(
(d) => d.kind === "OperationDefinition" && d.operation === "query"
// @ts-expect-error: name does not exist (?)
).name.value
console.log(`[gql] Response for ${env.CMS_URL}`, {
response,
operationName,
variables,
})
} catch (e) {
console.error(`[gql] Unable to extract operation name from query`, {
query,
error: e,
})
console.log(`[gql] Response for ${env.CMS_URL}`, {
response,
operationName: "<Unable to extract>",
variables,
})
}
return { data: response }
} catch (error) {
if (error instanceof ClientError) {
if (error.response.errors?.length) {
const failedToFetchItem = error.response.errors.find(
(err) => err.message === "Failed to fetch item"
)
if (
failedToFetchItem &&
failedToFetchItem.extensions?.errors === "Object not found!" &&
failedToFetchItem.path?.find((p) => Lang[p as Lang])
) {
/**
* Because of Contentstacks totally obscure way of implementing
* GraphQL where they throw an error when you are querying for
* a single item that is nullable and doesn't exist. This leads
* to the issue where when we have a page that is missing a published
* version for one language, it throws an error which we have to recover
* from here since it isn't an error.
*/
return { data: error.response.data as T }
}
}
}
console.error(
`[gql] Error sending graphql request to ${env.CMS_URL}`,
error
)
throw new Error("Something went wrong")
}
}