Files
web/server/routers/contentstack/contentPage/query.ts
2024-12-19 10:35:20 +00:00

105 lines
2.7 KiB
TypeScript

import { batchRequest } from "@/lib/graphql/batchRequest"
import {
GetContentPage,
GetContentPageBlocksBatch1,
GetContentPageBlocksBatch2,
} from "@/lib/graphql/Query/ContentPage/ContentPage.graphql"
import { contentstackExtendedProcedureUID, router } from "@/server/trpc"
import { contentPageSchema } from "./output"
import {
fetchContentPageRefs,
generatePageTags,
getContentPageCounter,
} from "./utils"
import {
TrackingChannelEnum,
type TrackingSDKPageData,
} from "@/types/components/tracking"
import type { GetContentPageSchema } from "@/types/trpc/routers/contentstack/contentPage"
import type { Lang } from "@/constants/languages"
export const contentPageQueryRouter = router({
get: contentstackExtendedProcedureUID.query(async ({ ctx }) => {
const { lang, uid } = ctx
const contentPageRefs = await fetchContentPageRefs(lang, uid)
if (!contentPageRefs) {
return null
}
const tags = generatePageTags(contentPageRefs, lang)
getContentPageCounter.add(1, { lang, uid })
console.info(
"contentstack.contentPage start",
JSON.stringify({
query: { lang, uid },
})
)
const contentPageRequest = await batchRequest<GetContentPageSchema>([
{
document: GetContentPage,
variables: { locale: lang, uid },
options: {
cache: "force-cache",
next: {
tags,
},
},
},
{
document: GetContentPageBlocksBatch1,
variables: { locale: lang, uid },
options: {
cache: "force-cache",
next: {
tags,
},
},
},
{
document: GetContentPageBlocksBatch2,
variables: { locale: lang, uid },
options: {
cache: "force-cache",
next: {
tags,
},
},
},
])
const contentPage = contentPageSchema.safeParse(contentPageRequest.data)
if (!contentPage.success) {
console.error(
`Failed to validate Contentpage Data - (lang: ${lang}, uid: ${uid})`
)
console.error(contentPage.error?.format())
return null
}
const tracking: TrackingSDKPageData = {
pageId: contentPage.data.content_page.system.uid,
domainLanguage: contentPage.data.content_page.system.locale as Lang,
publishedDate: contentPage.data.content_page.system.updated_at,
createdDate: contentPage.data.content_page.system.created_at,
channel: TrackingChannelEnum["static-content-page"],
pageType: "staticcontentpage",
pageName: contentPage.data.trackingProps.url,
siteSections: contentPage.data.trackingProps.url,
siteVersion: "new-web",
}
return {
contentPage: contentPage.data.content_page,
tracking,
}
}),
})