Files
web/utils/contentType.ts
2024-05-15 11:10:57 +02:00

79 lines
2.1 KiB
TypeScript

import { DocumentNode, print } from "graphql"
import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
import { GetContentTypeUid } from "@/lib/graphql/Query/ContentTypeUid.graphql"
import { validateContentTypeUid } from "@/types/requests/contentTypeUid"
export enum PageTypeEnum {
CurrentBlocksPage = "CurrentBlocksPage",
LoyaltyPage = "LoyaltyPage",
ContentPage = "ContentPage",
}
export async function getContentTypeByPathName(
pathNameWithoutLang: string,
lang = Lang.en
) {
const result = await fetch(env.CMS_URL, {
method: "POST",
headers: {
access_token: env.CMS_ACCESS_TOKEN,
"Content-Type": "application/json",
},
body: JSON.stringify({
query: print(GetContentTypeUid as DocumentNode),
variables: {
locale: lang,
url: pathNameWithoutLang,
},
}),
})
const pageTypeData = await result.json()
const validatedContentTypeUid = validateContentTypeUid.safeParse(
pageTypeData.data
)
if (!validatedContentTypeUid.success) {
console.error("Bad validation for `validatedContentTypeUid`")
console.error(validatedContentTypeUid.error)
return null
}
const pageType = validatedContentTypeUid.data
if (pageType.all_content_page.total) {
return PageTypeEnum.ContentPage
} else if (pageType.all_loyalty_page.total) {
return PageTypeEnum.LoyaltyPage
} else if (pageType.all_current_blocks_page.total) {
return PageTypeEnum.CurrentBlocksPage
}
}
/**
* Function to remove empty objects from a fetched content type.
* Used since Contentstack returns empty objects for all non
* queried in modular blocks.
*/
export function removeEmptyObjects<T>(obj: T): T {
const copy = obj as any
for (let key in copy) {
if (typeof copy[key] === "object" && copy[key] !== null) {
copy[key] = removeEmptyObjects(copy[key])
if (Object.keys(copy[key]).length === 0 && !Array.isArray(copy[key])) {
delete copy[key]
}
}
}
if (Array.isArray(copy)) {
return copy.filter((item) => item != null).map(removeEmptyObjects) as T
}
return copy as T
}