Skip to content

Commit

Permalink
chore(react-docs-page): throw when data loader gSP errors (#420)
Browse files Browse the repository at this point in the history
* feat: throw on gSP error

* chore: changeset

* chore: use `ContentApiError`

* chore: simplify `checkEnvVarsInDev` message

* chore: update snapshots

* chore: remove authorization header from tests
  • Loading branch information
thiskevinwang committed Nov 9, 2021
1 parent 44de9fb commit 523f802
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 59 deletions.
5 changes: 5 additions & 0 deletions .changeset/rare-cats-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hashicorp/react-docs-page': minor
---

Throw when getStaticProps errors
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,7 @@ need to reload your shell.
}
`;

exports[`contentApi fetchDocument should throw if a document is not found 1`] = `
"Failed to fetch: http://localhost:3001/api/content/waypoint/doc/latest/commands/k8s-bootstrap | {
\\"meta\\": {
\\"status_code\\": 404,
\\"status_text\\": \\"Not Found\\"
}
}"
`;
exports[`contentApi fetchDocument should throw if a document is not found 1`] = `"Failed to fetch: http://localhost:3001/api/content/waypoint/doc/latest/commands/k8s-bootstrap"`;

exports[`contentApi fetchNavData should return the requested navdata 1`] = `
Object {
Expand Down Expand Up @@ -382,14 +375,7 @@ Object {
}
`;

exports[`contentApi fetchNavData should throw if a navData is not found 1`] = `
"Failed to fetch: http://localhost:3001/api/content/waypoint/nav-data/v0.9000.x/commands | {
\\"meta\\": {
\\"status_code\\": 404,
\\"status_text\\": \\"Not Found\\"
}
}"
`;
exports[`contentApi fetchNavData should throw if a navData is not found 1`] = `"Failed to fetch: http://localhost:3001/api/content/waypoint/nav-data/v0.9000.x/commands"`;

exports[`contentApi fetchVersionMetadataList should return an empty list for invalid product name 1`] = `Array []`;

Expand Down
62 changes: 31 additions & 31 deletions packages/docs-page/content-api/index.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
const MKTG_CONTENT_API = process.env.MKTG_CONTENT_API
const MKTG_CONTENT_API_TOKEN = process.env.MKTG_CONTENT_API_TOKEN

const DEFAULT_HEADERS = {
headers: {
Authorization: `Bearer ${MKTG_CONTENT_API_TOKEN}`,
},
}

// Courtesy helper for warning about missing env vars during development
const checkEnvVarsInDev = () => {
if (process.env.NODE_ENV === 'development') {
if (!MKTG_CONTENT_API || !MKTG_CONTENT_API_TOKEN) {
if (!MKTG_CONTENT_API) {
const message = [
'Missing environment variables required to fetch remote content:',
!MKTG_CONTENT_API ? ' - `MKTG_CONTENT_API`' : false,
!MKTG_CONTENT_API_TOKEN ? ' - `MKTG_CONTENT_API_TOKEN`' : false,
'Reach out to #team-web-platform to get the proper values.'
].filter(Boolean).join('\n')
'Missing environment variable required to fetch remote content:',
' - `MKTG_CONTENT_API`',
'Reach out to #team-web-platform to get the proper value.',
].join('\n')
throw new Error(message)
}
}
}

export class ContentApiError extends Error {
name = 'ContentApiError' as const
constructor(message: string, public status: number) {
super(message)
}
}

export async function fetchNavData(
product: string, //: string, // waypoint
basePath: string, //: string, // commands | docs | plugins
Expand All @@ -31,14 +30,15 @@ export async function fetchNavData(

const fullPath = `nav-data/${version}/${basePath}`
const url = `${MKTG_CONTENT_API}/api/content/${product}/${fullPath}`
const response = await fetch(url, DEFAULT_HEADERS).then((res) => res.json())

if (response.meta.status_code !== 200) {
throw new Error(
`Failed to fetch: ${url} | ${JSON.stringify(response, null, 2)}`
)
const response = await fetch(url)

if (response.status !== 200) {
throw new ContentApiError(`Failed to fetch: ${url}`, response.status)
}
return response.result

const { result } = await response.json()
return result
}

export async function fetchDocument(
Expand All @@ -48,26 +48,26 @@ export async function fetchDocument(
checkEnvVarsInDev()

const url = `${MKTG_CONTENT_API}/api/content/${product}/${fullPath}`
const response = await fetch(url, DEFAULT_HEADERS).then((res) => res.json())
const response = await fetch(url)

if (response.meta.status_code !== 200) {
throw new Error(
`Failed to fetch: ${url} | ${JSON.stringify(response, null, 2)}`
)
if (response.status !== 200) {
throw new ContentApiError(`Failed to fetch: ${url}`, response.status)
}
return response.result

const { result } = await response.json()
return result
}

export async function fetchVersionMetadataList(product: string) {
checkEnvVarsInDev()

const url = `${MKTG_CONTENT_API}/api/content/${product}/version-metadata?partial=true`
const response = await fetch(url, DEFAULT_HEADERS).then((res) => res.json())
const response = await fetch(url)

if (response.meta.status_code !== 200) {
throw new Error(
`Failed to fetch: ${url} | ${JSON.stringify(response, null, 2)}`
)
if (response.status !== 200) {
throw new ContentApiError(`Failed to fetch: ${url}`, response.status)
}
return response.result

const { result } = await response.json()
return result
}
18 changes: 11 additions & 7 deletions packages/docs-page/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { GetStaticPaths, GetStaticProps, GetStaticPathsResult } from 'next'
import { ContentApiError } from '../content-api'
import FileSystemLoader from './loaders/file-system'
import RemoteContentLoader from './loaders/remote-content'
import { DataLoader } from './loaders/types'
Expand Down Expand Up @@ -45,10 +46,7 @@ export function getStaticGenerationFunctions(
}
case 'remote': {
const { strategy, ...restOpts } = opts

loader = new RemoteContentLoader({
...restOpts,
})
loader = new RemoteContentLoader({ ...restOpts })
}
}

Expand All @@ -68,10 +66,16 @@ export function getStaticGenerationFunctions(
revalidate: opts.revalidate,
}
} catch (err) {
console.error(err)
return {
notFound: true,
console.error(`Failed to generate static props:`, err)

if (err instanceof ContentApiError) {
if (err.status === 404) {
return {
notFound: true,
}
}
}
throw err
}
},
}
Expand Down
6 changes: 1 addition & 5 deletions packages/docs-page/server/loaders/remote-content.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,7 @@ describe('RemoteContentLoader', () => {

nock.disableNetConnect()

scope = nock(process.env.MKTG_CONTENT_API, {
reqheaders: {
authorization: `Bearer ${process.env.MKTG_CONTENT_API_TOKEN}`,
},
})
scope = nock(process.env.MKTG_CONTENT_API)
})

afterAll(() => {
Expand Down

1 comment on commit 523f802

@vercel
Copy link

@vercel vercel bot commented on 523f802 Nov 9, 2021

Choose a reason for hiding this comment

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

Please sign in to comment.