Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

404 page added #233

Merged
merged 4 commits into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 20 additions & 14 deletions src/lib/drupal/getGlobalElements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,33 @@ const nonSlugRoute = `${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}/jsonapi/banner-
// Helper function to fetch global elements for layout.
// It is called once for every page on build.
// TODO: add cache layer to drupalClient query results

export async function getGlobalElements(
jsonApiEntryPoint: string,
itemPath: string
jsonApiEntryPoint?: string,
itemPath?: string,
headerOnly: boolean = false
): Promise<LayoutProps> {
let banners = []

// If we are not in headerOnly mode and the necessary parameters are provided, fetch banners
// move all of this into @/data/queries/banners.ts
let bannerPath = `${jsonApiEntryPoint}/banner-alerts?item-path=${itemPath}`
if (!headerOnly && jsonApiEntryPoint && itemPath) {
let bannerPath = `${jsonApiEntryPoint}/banner-alerts?item-path=${itemPath}`

if (itemPath.includes('home')) {
bannerPath = `${nonSlugRoute}`
}
if (itemPath.includes('home')) {
bannerPath = nonSlugRoute
}

const requestBanner = await drupalClient.fetch(`${bannerPath}`)
const bannerData: [] | unknown = drupalClient.deserialize(
await requestBanner.json()
)
const banners = formatter(bannerData as NodeBanner[])
const requestBanner = await drupalClient.fetch(`${bannerPath}`)
const bannerData: [] | unknown = drupalClient.deserialize(
await requestBanner.json()
)
banners = formatter(bannerData as NodeBanner[])

// gather data for banners currently visible on this page
// const bannerData = await queries.getData('banner--alerts_lookup')
// gather data for banners currently visible on this page
// const bannerData = await queries.getData('banner--alerts_lookup')
}

// gather data for header and footer object
const headerFooterData = await queries.getData('header-footer-data')

return {
Expand Down
71 changes: 71 additions & 0 deletions src/pages/404.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React, { useEffect, useState } from 'react'
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Show resolved Hide resolved
import { recordEvent } from '@/lib/analytics/recordEvent'
import { Wrapper } from '@/templates/globals/wrapper'
import { getGlobalElements } from '@/lib/drupal/getGlobalElements'
import { CommonAndPopular } from '@/templates/common/commonAndPopular'

const Error404Page = ({ headerFooterData }) => {
useEffect(() => {
recordEvent({ event: 'nav-404-error' })
})
return (
<Wrapper bannerData={[]} headerFooterData={headerFooterData}>
<div className="main maintenance-page" role="main">
<div className="primary">
<div className="row">
<div className="text-center usa-content">
<h3>Sorry — we can’t find that page</h3>
<p>Try the search box or one of the common questions below.</p>
<div className="feature va-flex va-flex--ctr">
<form
acceptCharset="UTF-8"
action="/search/"
id="search_form"
className="full-width"
method="get"
>
<div className="va-flex va-flex--top va-flex--jctr">
<label htmlFor="mobile-query">Search:</label>
<input
autoComplete="off"
className="usagov-search-autocomplete full-width"
id="mobile-query"
name="query"
type="text"
/>
<input type="submit" value="Search" />
</div>
</form>
</div>
</div>
</div>
</div>

<CommonAndPopular />
</div>
</Wrapper>
)
}

export async function getStaticProps() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I would restructure this to match [[...slug]].tsx a little closer, unless there's a specific reason that the 404 page needs handled in this way.

const { headerFooterData } = await getGlobalElements() feels a bit cleaner than the let & try catch block. slug has the whole getStaticProps function in a try catch

// You can use your getGlobalElements function or any other function to fetch your data
let headerFooterData = {}

try {
const globalData = await getGlobalElements(undefined, undefined, true)
headerFooterData = globalData.headerFooterData || {}
} catch (error) {
// If there's an error, you'll receive it here. You might want to log this or handle it appropriately.
console.error('Failed to fetch global elements:', error)
}

// Return the fetched data as props
return {
props: {
headerFooterData,
},
revalidate: 60, // Optionally, you can enable ISR by setting a revalidation period
jtmst marked this conversation as resolved.
Show resolved Hide resolved
}
}

export default Error404Page
32 changes: 32 additions & 0 deletions src/pages/tests/Error404Page.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
import Error404Page from '../404'

// Mocks for analytics event
jest.mock('@/lib/analytics/recordEvent', () => ({
recordEvent: jest.fn(),
}))

jest.mock('@/templates/globals/wrapper', () => ({
Wrapper: ({ children }) => <div>{children}</div>,
}))

describe('Error404Page', () => {
it('renders without crashing', () => {
render(<Error404Page headerFooterData={{}} />)
expect(
screen.getByText('Sorry — we can’t find that page')
).toBeInTheDocument()
})

it('displays the search box', () => {
render(<Error404Page headerFooterData={{}} />)
expect(screen.getByRole('textbox')).toBeInTheDocument()
})

it('displays common questions and popular links', () => {
render(<Error404Page headerFooterData={{}} />)
expect(screen.getByText('Common Questions')).toBeInTheDocument()
expect(screen.getByText('Popular on VA.gov')).toBeInTheDocument()
})
})
52 changes: 52 additions & 0 deletions src/templates/common/commonAndPopular/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React from 'react'
import Link from 'next/link'

export function CommonAndPopular() {
return (
<div className="row va-quicklinks va-quicklinks--commpop">
<div className="small-12 usa-width-one-half medium-6 columns">
<h3 className="va-h-ruled">Common Questions</h3>
<ul className="va-list--plain">
<li>
<Link href="/health-care/how-to-apply/">
How do I apply for health care?
</Link>
</li>
<li>
<Link href="/disability/how-to-file-claim/">
How do I file for disability benefits?
</Link>
</li>
<li>
<Link href="/education/how-to-apply/">
How do I apply for education benefits?
</Link>
</li>
</ul>
</div>
<div className="small-12 usa-width-one-half medium-6 columns">
<h3 className="va-h-ruled">Popular on VA.gov</h3>
<ul className="va-list--plain">
<li>
<Link href="/find-locations/">Find nearby VA locations</Link>
</li>
<li>
<Link href="/education/gi-bill-comparison-tool">
View education benefits available by school
</Link>
</li>
<li>
<a
href="https://www.veteranscrisisline.net/"
target="_blank"
rel="noopener noreferrer"
className="external no-external-icon"
>
Contact the Veterans Crisis Line
</a>
</li>
</ul>
</div>
</div>
)
}