Skip to content

Commit

Permalink
Small refactors for better caches
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish committed Oct 7, 2024
1 parent 8636bc1 commit 1cf56e6
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 32 deletions.
5 changes: 2 additions & 3 deletions app/[...slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ export const dynamic = "force-static"
export const maxDuration = 60

const Page = async ({params}: PageProps) => {
const {redirect: redirectPath, entity, error} = await getEntityFromPath<NodeUnion>(getPathFromContext({params}))
const {redirect: redirectPath, entity} = await getEntityFromPath<NodeUnion>(getPathFromContext({params}))

if (error) throw error
if (redirectPath?.url) redirect(redirectPath.url)
if (redirectPath) redirect(redirectPath)
if (!entity) notFound()

return <NodePage node={entity} />
Expand Down
4 changes: 2 additions & 2 deletions app/api/revalidate/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const GET = async (request: NextRequest) => {
let path = request.nextUrl.searchParams.get("slug")
if (!path || path.startsWith("/node/")) return NextResponse.json({message: "Invalid slug"}, {status: 403})

const tagsInvalidated = ["paths", `paths:${path}`]
const tagsInvalidated = path.startsWith("/tags/") ? [] : [`paths:${path}`]
if (path.startsWith("/tags/"))
path
.substring(6)
Expand All @@ -30,7 +30,7 @@ export const GET = async (request: NextRequest) => {

// When the home page is saved, it's url slug might be like `/home`. If the home page matches the slug, invalidate
// the home page path.
if ((await getHomePagePath()) === path) tagsInvalidated.push("paths:/")
if (!path.startsWith("/tags/") && (await getHomePagePath()) === path) tagsInvalidated.push("paths:/")

tagsInvalidated.map(tag => revalidateTag(tag))

Expand Down
4 changes: 1 addition & 3 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ export const revalidate = false
export const dynamic = "force-static"

const Home = async () => {
const {entity, error} = await getEntityFromPath<NodeStanfordPage>("/", isPreviewMode())

if (error) throw error
const {entity} = await getEntityFromPath<NodeStanfordPage>("/", isPreviewMode())
if (!entity) notFound()

return (
Expand Down
4 changes: 1 addition & 3 deletions app/preview/[...slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ import {isPreviewMode} from "@lib/drupal/is-preview-mode"

const PreviewPage = async ({params}: PageProps) => {
if (!isPreviewMode()) notFound()
const {entity, error} = await getEntityFromPath<NodeUnion>(getPathFromContext({params}), isPreviewMode())

if (error) throw error
const {entity} = await getEntityFromPath<NodeUnion>(getPathFromContext({params}), isPreviewMode())
if (!entity) notFound()

return (
Expand Down
10 changes: 2 additions & 8 deletions app/sitemap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,14 @@ import {graphqlClient} from "@lib/gql/gql-client"
import {NodeUnion} from "@lib/gql/__generated__/drupal"

// https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
export const revalidate = false
export const revalidate = 25200
export const dynamic = "force-static"

const Sitemap = async (): Promise<MetadataRoute.Sitemap> => {
const nodeQuery = await graphqlClient({next: {revalidate: 60 * 60 * 7}}).AllNodes()
const nodeQuery = await graphqlClient({cache: "no-cache"}).AllNodes()
const nodes: NodeUnion[] = []

// nodeQuery.nodeStanfordCourses.nodes.map(node => nodes.push(node as NodeUnion))
// nodeQuery.nodeStanfordEventSeriesItems.nodes.map(node => nodes.push(node as NodeUnion))
// nodeQuery.nodeStanfordEvents.nodes.map(node => nodes.push(node as NodeUnion))
// nodeQuery.nodeStanfordNewsItems.nodes.map(node => nodes.push(node as NodeUnion))
nodeQuery.nodeStanfordPages.nodes.map(node => nodes.push(node as NodeUnion))
// nodeQuery.nodeStanfordPeople.nodes.map(node => nodes.push(node as NodeUnion))
// nodeQuery.nodeStanfordPolicies.nodes.map(node => nodes.push(node as NodeUnion))
nodeQuery.nodeSumSummerCourses.nodes.map(node => nodes.push(node as NodeUnion))

const sitemap: MetadataRoute.Sitemap = []
Expand Down
32 changes: 19 additions & 13 deletions src/lib/gql/gql-queries.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,20 @@ import {
import {cache} from "react"
import {graphqlClient} from "@lib/gql/gql-client"
import {unstable_cache as nextCache} from "next/cache"
import {ClientError} from "graphql-request"
import {GraphQLError} from "graphql/error"

type DrupalClientError = GraphQLError & {
debugMessage: string
}

export const getEntityFromPath = cache(
async <T extends NodeUnion | TermUnion>(
path: string,
previewMode?: boolean
): Promise<{
entity?: T
redirect?: RouteRedirect
error?: string
redirect?: RouteRedirect["url"]
}> => {
"use server"

Expand All @@ -33,16 +38,23 @@ export const getEntityFromPath = cache(
if (path.startsWith("/node/")) return {}

try {
query = await graphqlClient({next: {tags: ["all-entities", `paths:${path}`]}}, previewMode).Route({path})
query = await graphqlClient({cache: "no-cache"}, previewMode).Route({path})
} catch (e) {
console.warn(e instanceof Error ? e.message : "An error occurred")
return {entity: undefined, redirect: undefined, error: e instanceof Error ? e.message : "An error occurred"}
if (e instanceof ClientError) {
// @ts-ignore
const messages = e.response.errors?.map((error: DrupalClientError) => error.debugMessage)
console.warn([...new Set(messages)].join(" "))
} else {
console.warn(e instanceof Error ? e.message : "An error occurred")
}
return {}
}

if (query.route?.__typename === "RouteRedirect") return {redirect: query.route, entity: undefined}
if (query.route?.__typename === "RouteRedirect") return {redirect: query.route.url}
entity =
query.route?.__typename === "RouteInternal" && query.route.entity ? (query.route.entity as T) : undefined
return {entity, redirect: undefined, error: undefined}

return {entity}
},
["entities", path, previewMode ? "preview" : "anonymous"],
{tags: ["all-entities", `paths:${path}`]}
Expand Down Expand Up @@ -126,13 +138,7 @@ export const getAllNodePaths = nextCache(

const nodeQuery = await graphqlClient({next: {tags: ["paths"]}}).AllNodes({first: 1000})
const nodePaths: string[] = []
// nodeQuery.nodeStanfordCourses.nodes.map(node => nodePaths.push(node.path))
// nodeQuery.nodeStanfordEventSeriesItems.nodes.map(node => nodePaths.push(node.path))
// nodeQuery.nodeStanfordEvents.nodes.map(node => nodePaths.push(node.path))
// nodeQuery.nodeStanfordNewsItems.nodes.map(node => nodePaths.push(node.path))
nodeQuery.nodeStanfordPages.nodes.map(node => nodePaths.push(node.path))
// nodeQuery.nodeStanfordPeople.nodes.map(node => nodePaths.push(node.path))
// nodeQuery.nodeStanfordPolicies.nodes.map(node => nodePaths.push(node.path))
nodeQuery.nodeSumSummerCourses.nodes.map(node => nodePaths.push(node.path))
return nodePaths
}),
Expand Down

0 comments on commit 1cf56e6

Please sign in to comment.