Skip to content

Commit

Permalink
Clear TS issues on lib
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish committed Nov 9, 2023
1 parent 99d2458 commit 5d2587e
Show file tree
Hide file tree
Showing 17 changed files with 115 additions and 144 deletions.
11 changes: 6 additions & 5 deletions app/[...slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,19 @@ class RedirectError extends Error {
}

const getPageData = async(params: Params): Promise<StanfordNode | undefined> => {
const draftDev = isDraftMode()
const accessToken = draftDev ? await getAccessToken(true) : null;
const draftMode = isDraftMode()
const accessToken = draftMode ? await getAccessToken(true) : null;

const path = await translatePathFromContext({params}, accessToken ? {accessToken} : {});
// Check for redirect.
if (path?.redirect?.[0].to) {
if (path?.redirect && path?.redirect?.[0].to) {
const currentPath = '/' + (typeof params?.slug === 'object' ? params.slug.join('/') : params?.slug);
const [destination] = path.redirect;

const [destination] = path.redirect;
if (destination.to != currentPath) {
throw new RedirectError(destination.to);
}

}

if (!path || !path.jsonapi) {
Expand All @@ -51,7 +52,7 @@ const getPageData = async(params: Params): Promise<StanfordNode | undefined> =>
if (params?.slug?.[0] === 'node' && path?.entity?.path) {
throw new RedirectError(path.entity.path);
}
return getResourceFromContext<StanfordNode>(path.jsonapi.resourceName, {params}, {}, draftDev)
return getResourceFromContext<StanfordNode>(path.jsonapi.resourceName, {params}, {draftMode})
}

export const generateStaticParams = async () => {
Expand Down
2 changes: 1 addition & 1 deletion app/api/draft/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export async function GET(request: Request) {

// Fetch the headless CMS to check if the provided `slug` exists
// getPostBySlug would implement the required fetching logic to the headless CMS
const node = await getResourceByPath<StanfordNode>(slug, {}, true)
const node = await getResourceByPath<StanfordNode>(slug, {draftMode: true})

// If the slug doesn't exist prevent draft mode from being enabled
if (!node) {
Expand Down
6 changes: 3 additions & 3 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ export const metadata = {
export const revalidate = 3600;

const RootLayout = ({children, modal}: { children: React.ReactNode, modal?: React.ReactNode }) => {
const draftDev = isDraftMode();
const draftMode = isDraftMode();
return (
<html lang="en" className={`${sourceSansPro.className} font-sans`}>
{draftDev && <Editori11y/>}
{(!draftDev && process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID) &&
{draftMode && <Editori11y/>}
{(!draftMode && process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID) &&
<>
<Script async src="//siteimproveanalytics.com/js/siteanalyze_80352.js"/>
<GoogleAnalytics/>
Expand Down
4 changes: 2 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import {notFound} from "next/navigation";
export const revalidate = 86400;

const Home = async () => {
const draftDev = isDraftMode()
const node = await getResourceByPath<BasicPageNodeType>('/', {}, draftDev);
const draftMode = isDraftMode()
const node = await getResourceByPath<BasicPageNodeType>('/', {draftMode});
if(!node) notFound();

return (
Expand Down
4 changes: 2 additions & 2 deletions src/components/global/page-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import {GlobalMessageConfigPageType, LockupSettingsConfigPageType, SiteSettingsC
import {isDraftMode} from "@lib/drupal/utils";

const PageHeader = async () => {
const draftDev = isDraftMode();
const {tree} = await getMenu('main', {}, draftDev)
const draftMode = isDraftMode();
const {tree} = await getMenu('main', {draftMode})
const globalMessage = await getConfigPageResource<GlobalMessageConfigPageType>('stanford_global_message');
const siteSettings = await getConfigPageResource<SiteSettingsConfigPageType>('stanford_basic_site_settings')
const lockupSettings = await getConfigPageResource<LockupSettingsConfigPageType>('lockup_settings')
Expand Down
4 changes: 2 additions & 2 deletions src/components/layouts/interior-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import {PropsWithChildren} from "react";
import {isDraftMode} from "@lib/drupal/utils";

const InteriorPage = async ({children, currentPath}: PropsWithChildren<{ currentPath: string }>) => {
const draftDev = isDraftMode();
const {tree} = await getMenu('main', {}, draftDev);
const draftMode = isDraftMode();
const {tree} = await getMenu('main', {draftMode});

return (
<div className="centered flex gap-20">
Expand Down
4 changes: 2 additions & 2 deletions src/components/paragraphs/paragraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ interface Props {
}

const Paragraph = async ({paragraph}: Props): Promise<JSX.Element | undefined> => {
const draftDev = isDraftMode()
paragraph = await getResource<StanfordParagraph>(paragraph.type, paragraph.id, {}, draftDev);
const draftMode = isDraftMode()
paragraph = await getResource<StanfordParagraph>(paragraph.type, paragraph.id, {draftMode});

switch (paragraph.type) {
case 'paragraph--stanford_banner':
Expand Down
31 changes: 20 additions & 11 deletions src/components/paragraphs/rows/rows.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,30 @@ import OneColumn from "@components/paragraphs/rows/one-column";
import TwoColumn from "@components/paragraphs/rows/two-column";
import ThreeColumn from "@components/paragraphs/rows/three-column";
import {getResources} from "@lib/drupal/get-resource";
import {LayoutParagraphsBehaviorsType, StanfordParagraph} from "@lib/types";
import {LayoutParagraphsBehaviorsType, LayoutParagraphType, StanfordParagraph} from "@lib/types";
import {isDraftMode} from "@lib/drupal/utils";

interface LayoutsProps {
[key: string]: StanfordParagraph

interface Layout {
[key: string]: {
item: LayoutParagraphType
children: StanfordParagraph[]
}
}

const Rows = async ({components}: { components: StanfordParagraph[] }) => {
const layouts: LayoutsProps = {};
const layouts: Layout = {};

const draftDev = isDraftMode();
components = await getResources<StanfordParagraph>(components, draftDev);
const draftMode = isDraftMode();
components = await getResources<StanfordParagraph>(components, draftMode);

// Set the layouts first.
components.map(item => {
if (item.behavior_settings?.layout_paragraphs?.layout) {
layouts[item.id] = item;
layouts[item.id].children = [];
if (item.type === 'paragraph--stanford_layout') {
layouts[item.id] = {
item,
children: []
}
}
})

Expand All @@ -36,15 +42,18 @@ const Rows = async ({components}: { components: StanfordParagraph[] }) => {
{Object.keys(layouts).map(layoutId =>
<Row
key={layoutId}
layoutSettings={layouts[layoutId].behavior_settings?.layout_paragraphs}
layoutSettings={layouts[layoutId].item.behavior_settings?.layout_paragraphs}
items={layouts[layoutId].children}
/>
)}
</div>
)
}

const Row = ({layoutSettings, items}: { layoutSettings: LayoutParagraphsBehaviorsType | undefined, items: StanfordParagraph[] }) => {
const Row = ({layoutSettings, items}: {
layoutSettings: LayoutParagraphsBehaviorsType | undefined,
items: StanfordParagraph[]
}) => {
return (
<>
{layoutSettings?.layout === 'layout_paragraphs_1_column' &&
Expand Down
4 changes: 2 additions & 2 deletions src/lib/drupal/deserialize.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// @ts-nocheck
import Jsona from "jsona";
import {TDeserializeOptions, TJsonApiBody} from "jsona/src/JsonaTypes";

const dataFormatter = new Jsona()

export const deserialize = (body, options?) => {
export const deserialize = (body:TJsonApiBody | string, options?: TDeserializeOptions) => {
if (!body) return null
return dataFormatter.deserialize(body, options)
}
2 changes: 1 addition & 1 deletion src/lib/drupal/get-access-token.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// @ts-nocheck

// import { draftMode } from 'next/headers'
import {cache} from "./get-cache"

Expand Down
47 changes: 19 additions & 28 deletions src/lib/drupal/get-menu.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,27 @@
// @ts-nocheck

import {AccessToken, DrupalMenuLinkContent, JsonApiWithLocaleOptions} from "next-drupal";
import {AccessToken, JsonApiWithLocaleOptions} from "next-drupal";
import {DrupalMenuLinkContent} from "@lib/types"
import {buildUrl, buildHeaders} from "./utils";
import {deserialize} from "@lib/drupal/deserialize";

export async function getMenu<T extends DrupalMenuLinkContent>(
export async function getMenu(
name: string,
options?: {
deserialize?: boolean
accessToken?: AccessToken
draftMode: boolean
} & JsonApiWithLocaleOptions,
draftMode: boolean = false
): Promise<{
items: T[]
tree: T[]
}> {
): Promise<{ items: DrupalMenuLinkContent[], tree: DrupalMenuLinkContent[] }> {

options = {
deserialize: true,
draftMode: false,
...options,
}

const localePrefix =
options?.locale && options.locale !== options.defaultLocale
? `/${options.locale}`
: ""

const url = buildUrl(`${localePrefix}/jsonapi/menu_items/${name}`)
const url = buildUrl(`/jsonapi/menu_items/${name}`)

const response = await fetch(url.toString(), {
headers: await buildHeaders(options, draftMode),
headers: await buildHeaders(options),
})

if (!response.ok) {
Expand All @@ -37,14 +30,14 @@ export async function getMenu<T extends DrupalMenuLinkContent>(

const data = await response.json()

let items = options.deserialize ? deserialize(data) : data
let items: DrupalMenuLinkContent[] = options.deserialize ? deserialize(data) : data;
items = items.map(item => ({
id: item.id,
title: item.title,
url: item.url,
parent: item.parent,
expanded: item.expanded
}));
} as DrupalMenuLinkContent));
const {items: tree} = buildMenuTree(items)

return {
Expand All @@ -54,10 +47,10 @@ export async function getMenu<T extends DrupalMenuLinkContent>(
}


function buildMenuTree(
function buildMenuTree<T extends DrupalMenuLinkContent>(
links: DrupalMenuLinkContent[],
parent: DrupalMenuLinkContent["id"] = ""
) {
): { items: DrupalMenuLinkContent[] } {
if (!links?.length) {
return {
items: [],
Expand All @@ -66,12 +59,10 @@ function buildMenuTree(

const children = links.filter((link) => link.parent === parent)

return children.length
? {
items: children.map((link) => ({
...link,
...buildMenuTree(links, link.id),
})),
}
: {}
return children.length ? {
items: children.map((link) => ({
...link,
...buildMenuTree(links, link.id),
})),
} : {items: []}
}
40 changes: 8 additions & 32 deletions src/lib/drupal/get-paths.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
// @ts-nocheck

import {GetStaticPathsContext, GetStaticPathsResult} from "next";
import {AccessToken, JsonApiParams, Locale} from "next-drupal";
import {AccessToken, JsonApiParams, JsonApiResource, JsonApiResourceWithPath} from "next-drupal";
import {getResourceCollection} from "@lib/drupal/get-resource";

export const getPathsFromContext = async (
Expand All @@ -11,7 +9,7 @@ export const getPathsFromContext = async (
params?: JsonApiParams
accessToken?: AccessToken
} = {}
): Promise<GetStaticPathsResult["paths"]> =>{
): Promise<GetStaticPathsResult["paths"]> => {
if (typeof types === "string") {
types = [types]
}
Expand All @@ -25,37 +23,19 @@ export const getPathsFromContext = async (
...options?.params,
}

// Handle localized path aliases
if (!context.locales?.length) {
const resources = await getResourceCollection(type, {
deserialize: true,
...options,
})

return buildPathsFromResources(resources)
}

const paths = await Promise.all(
context.locales.map(async (locale) => {
const resources = await getResourceCollection(type, {
deserialize: true,
locale,
defaultLocale: context.defaultLocale,
...options,
})
const resources = await getResourceCollection<JsonApiResourceWithPath[]>(type, {
deserialize: true,
...options,
})

return buildPathsFromResources(resources, locale)
})
)

return paths.flat()
return buildPathsFromResources(resources)
})
)

return paths.flat()
}

function buildPathsFromResources(resources, locale?: Locale) {
function buildPathsFromResources(resources: JsonApiResourceWithPath[]) {
return resources?.flatMap((resource) => {
const slug =
resource?.path?.alias === process.env.DRUPAL_FRONT_PAGE
Expand All @@ -68,10 +48,6 @@ function buildPathsFromResources(resources, locale?: Locale) {
},
}

if (locale) {
path["locale"] = locale
}

return path
})
}
Loading

0 comments on commit 5d2587e

Please sign in to comment.