Skip to content

Commit

Permalink
fix: Page error codes (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
tlgimenes authored Jun 13, 2022
1 parent 7e934df commit db5c414
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 50 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Removed

### Fixed
- Status code when error occurs (404/500) ([#108](https://github.com/vtex-sites/gatsby.store/pull/108))

### Security

Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@
"@envelop/graphql-jit": "^1.1.1",
"@envelop/parser-cache": "^2.2.0",
"@envelop/validation-cache": "^2.2.0",
"@faststore/api": "^1.9.3",
"@faststore/sdk": "^1.9.2",
"@faststore/ui": "^1.9.2",
"@faststore/api": "^1.9.6",
"@faststore/sdk": "^1.9.4",
"@faststore/ui": "^1.9.4",
"@vtex/graphql-utils": "^1.8.42",
"gatsby": "^4.14.1",
"gatsby-plugin-gatsby-cloud": "^4.14.0",
Expand Down
12 changes: 7 additions & 5 deletions src/api/graphql.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isFastStoreError } from '@faststore/api'
import type { GatsbyFunctionRequest, GatsbyFunctionResponse } from 'gatsby'

import { execute } from '../server'
Expand Down Expand Up @@ -35,7 +36,7 @@ const handler = async (
const { operationName, variables, query } = parseRequest(req)

try {
const response = await execute(
const result = await execute(
{
operationName,
variables,
Expand All @@ -44,14 +45,15 @@ const handler = async (
{ req }
)

if (Array.isArray(response.errors)) {
// TODO: Return 400 on userError
res.status(500)
if (Array.isArray(result.errors)) {
const error = result.errors.find(isFastStoreError)

res.status(error?.extensions.status ?? 500)
}

res.setHeader('cache-control', 'no-cache, no-store')
res.setHeader('content-type', 'application/json')
res.send(JSON.stringify(response))
res.send(JSON.stringify(result))
} catch (err) {
console.error(err)

Expand Down
32 changes: 20 additions & 12 deletions src/pages/[...slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ type Props = PageProps<
CollectionPageQueryQuery,
CollectionPageQueryQueryVariables,
unknown,
ServerCollectionPageQueryQuery
ServerCollectionPageQueryQuery | null
> & { slug: string }

const useSearchParams = (props: Props): SearchState => {
const {
location: { href, pathname },
serverData: { collection },
serverData,
} = props

const selectedFacets = collection?.meta.selectedFacets
const selectedFacets = serverData?.collection?.meta.selectedFacets

return useMemo(() => {
const maybeState = href ? parseSearchState(new URL(href)) : null
Expand All @@ -56,14 +56,20 @@ const useSearchParams = (props: Props): SearchState => {
function Page(props: Props) {
const {
data: { site },
serverData: { collection },
serverData,
location: { host },
slug,
} = props

const { locale } = useSession()
const searchParams = useSearchParams(props)

// No data was found
if (serverData === null) {
return null
}

const { collection } = serverData
const { page } = searchParams
const title = collection?.seo.title ?? site?.siteMetadata?.title ?? ''
const pageQuery = page !== 0 ? `?page=${page}` : ''
Expand Down Expand Up @@ -176,35 +182,37 @@ export const getServerData = async ({
params: Record<string, string>
}) => {
const ONE_YEAR_CACHE = `s-maxage=31536000, stale-while-revalidate`

const { isNotFoundError } = await import('@faststore/api')
const { execute } = await import('src/server/index')
const { data, errors } = await execute({
const { data, errors = [] } = await execute({
operationName: querySSR,
variables: { slug },
})

if (errors && errors?.length > 0) {
throw new Error(`${errors[0]}`)
}
const notFound = errors.find(isNotFoundError)

if (data === null) {
if (notFound) {
const params = new URLSearchParams({
from: encodeURIComponent(`/${slug}`),
})

return {
status: 301,
props: {},
props: null,
headers: {
'cache-control': ONE_YEAR_CACHE,
location: `/404/?${params.toString()}}`,
},
}
}

if (errors.length > 0) {
throw errors[0]
}

return {
status: 200,
props: data ?? {},
props: data,
headers: {
'cache-control': ONE_YEAR_CACHE,
},
Expand Down
28 changes: 18 additions & 10 deletions src/pages/[slug]/p.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,24 @@ export type Props = PageProps<
ProductPageQueryQuery,
ProductPageQueryQueryVariables,
unknown,
ServerProductPageQueryQuery
ServerProductPageQueryQuery | null
> & { slug: string }

function Page(props: Props) {
const { locale, currency } = useSession()
const {
data: { site },
serverData: { product },
serverData,
location: { host },
slug,
} = props

// No data was found
if (serverData === null) {
return null
}

const { product } = serverData
const title = product?.seo.title ?? site?.siteMetadata?.title ?? ''
const description =
product?.seo.description ?? site?.siteMetadata?.description ?? ''
Expand Down Expand Up @@ -185,37 +191,39 @@ export const getServerData = async ({
params: Record<string, string>
}) => {
const ONE_YEAR_CACHE = `s-maxage=31536000, stale-while-revalidate`

const id = slug.split('-').pop()

const { isNotFoundError } = await import('@faststore/api')
const { execute } = await import('src/server/index')
const { data, errors } = await execute({
const { data, errors = [] } = await execute({
operationName: querySSR,
variables: { id },
})

if (errors && errors?.length > 0) {
throw new Error(`${errors[0]}`)
}
const notFound = errors.find(isNotFoundError)

if (data === null) {
if (notFound) {
const params = new URLSearchParams({
from: encodeURIComponent(`/${slug}/p`),
})

return {
status: 301,
props: {},
props: null,
headers: {
'cache-control': ONE_YEAR_CACHE,
location: `/404/?${params.toString()}}`,
},
}
}

if (errors.length > 0) {
throw errors[0]
}

return {
status: 200,
props: data ?? {},
props: data,
headers: {
'cache-control': ONE_YEAR_CACHE,
},
Expand Down
12 changes: 4 additions & 8 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { FormatErrorHandler } from '@envelop/core'
import { useGraphQlJit } from '@envelop/graphql-jit'
import { useParserCache } from '@envelop/parser-cache'
import { useValidationCache } from '@envelop/validation-cache'
import { getContextFactory, getSchema } from '@faststore/api'
import { getContextFactory, getSchema, isFastStoreError } from '@faststore/api'
import type { Options as APIOptions } from '@faststore/api'
import { GraphQLError } from 'graphql'

Expand Down Expand Up @@ -40,17 +40,13 @@ export const apiSchema = getSchema(apiOptions)

const apiContextFactory = getContextFactory(apiOptions)

const isBadRequestError = (err: GraphQLError) => {
return err.originalError && err.originalError.name === 'BadRequestError'
}

const formatError: FormatErrorHandler = (err) => {
console.error(err)

if (err instanceof GraphQLError && isBadRequestError(err)) {
if (err instanceof GraphQLError && isFastStoreError(err.originalError)) {
return err
}

console.error(err)

return new GraphQLError('Sorry, something went wrong.')
}

Expand Down
24 changes: 12 additions & 12 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1974,10 +1974,10 @@
minimatch "^3.0.4"
strip-json-comments "^3.1.1"

"@faststore/api@^1.9.3":
version "1.9.3"
resolved "https://registry.yarnpkg.com/@faststore/api/-/api-1.9.3.tgz#26afdade5bdbbd908b6c6d03f8a7f848898bfab1"
integrity sha512-1l2/bxxIJL9pOblQsbCH/Lm577eTaRLn1tkZQ+bFTb1+NzrZl58BAKgv5FqCVqzBG7X1GcoVIq+q3G+MsB6dEQ==
"@faststore/api@^1.9.6":
version "1.9.6"
resolved "https://registry.yarnpkg.com/@faststore/api/-/api-1.9.6.tgz#c94c32fc2fb2098d6016914475b508e3f9afcf42"
integrity sha512-J3zi7g+szhQBLU9jgYgFDwP4oQFJB+4BpFx/Qvtn6voRsScRoP1Sz9Yk/1lZ2t1T5IZFTn4Qw/oudK2ii5+hMA==
dependencies:
"@graphql-tools/schema" "^8.2.0"
"@rollup/plugin-graphql" "^1.0.0"
Expand All @@ -1986,17 +1986,17 @@
isomorphic-unfetch "^3.1.0"
p-limit "^3.1.0"

"@faststore/sdk@^1.9.2":
version "1.9.2"
resolved "https://registry.yarnpkg.com/@faststore/sdk/-/sdk-1.9.2.tgz#9e0b302f0d20333af0681be10013996493e94f09"
integrity sha512-sOoa9Axex0V3byvcCXkBuJSbfXcVnNrQxiovX4TaIWK2dcIx6+NnTKrQS8aTcaCwxmj1zACCw3lDt4yn06zR2w==
"@faststore/sdk@^1.9.4":
version "1.9.4"
resolved "https://registry.yarnpkg.com/@faststore/sdk/-/sdk-1.9.4.tgz#fa041160e6f90d789866ee9176da2ff4336b9d8b"
integrity sha512-emdCI738A3IBY0hrsR+Gs63eg2/ZDSllHObdbJnMemodTTY3rEYKA00KvBz7zTkkFydkWYXs3tKO0NfM+kO8WA==
dependencies:
idb-keyval "^5.1.3"

"@faststore/ui@^1.9.2":
version "1.9.2"
resolved "https://registry.yarnpkg.com/@faststore/ui/-/ui-1.9.2.tgz#3ae00b0c72a79892113b46676741bd12fd876f7a"
integrity sha512-yDMkDaOgOfRciHj7PiIBQdYwXsbdwmAOMVbO9cgP3brmE+9didi2FFI7spZicSjLnje3SLeaBQ/n3ETaM29TRA==
"@faststore/ui@^1.9.4":
version "1.9.4"
resolved "https://registry.yarnpkg.com/@faststore/ui/-/ui-1.9.4.tgz#fb76491f476fc3a1dac0a5dbf7da013a8e9bd69b"
integrity sha512-IC8CzxiZU91UDV5FGdMrBD/HiMXS8JLZt0cJ2iCbJWHzpU0p40ja7GGP6DIxKCuauW++T5zeHg5rB4VF3T7/nQ==
dependencies:
"@reach/popover" "^0.16.0"
"@storybook/addon-a11y" "^6.4.4"
Expand Down

1 comment on commit db5c414

@vercel
Copy link

@vercel vercel bot commented on db5c414 Jun 13, 2022

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.