Tested basic revalidation

This commit is contained in:
Henrik Larsson 2023-05-23 10:29:10 +02:00
parent 90a808b8b1
commit d58d05df47
5 changed files with 803 additions and 685 deletions

View File

@ -16,40 +16,28 @@ import SinglePagePreview from './single-page-preview';
/** /**
* Render pages depending on type. * Render pages depending on type.
*/ */
export default async function Page({ export default async function Page({ params }: { params: { slug: string[]; locale: string } }) {
params,
}: {
params: { slug: string[], locale: string };
}) {
const { isEnabled } = draftMode(); const { isEnabled } = draftMode();
const { slug, locale } = params; const { slug, locale } = params;
const { query = '', queryParams, docType } = getQueryFromSlug(slug, locale)
const pageData = await client.fetch(query, queryParams) const { query = '', queryParams, docType } = getQueryFromSlug(slug, locale);
const data = filterDataToSingleItem(pageData, isEnabled) const pageData = await client.fetch(query, queryParams);
const data = filterDataToSingleItem(pageData, isEnabled);
if (isEnabled) { if (isEnabled) {
return ( return (
<PreviewSuspense fallback="Loading..."> <PreviewSuspense fallback="Loading...">
{docType === 'home' && ( {docType === 'home' && <HomePagePreview query={query} queryParams={queryParams} />}
<HomePagePreview query={query} queryParams={queryParams} /> {docType === 'page' && <SinglePagePreview query={query} queryParams={queryParams} />}
)} {docType === 'product' && <ProductPagePreview query={query} queryParams={queryParams} />}
{docType === 'page' && ( {docType === 'category' && <CategoryPagePreview query={query} queryParams={queryParams} />}
<SinglePagePreview query={query} queryParams={queryParams} />
)}
{docType === 'product' && (
<ProductPagePreview query={query} queryParams={queryParams} />
)}
{docType === 'category' && (
<CategoryPagePreview query={query} queryParams={queryParams} />
)}
</PreviewSuspense> </PreviewSuspense>
) );
} }
return ( return (
<> <>
{docType === 'home' && <HomePage data={data} />} {docType === 'home' && <HomePage data={data} />}
@ -57,25 +45,22 @@ export default async function Page({
{docType === 'category' && <CategoryPage data={data} />} {docType === 'category' && <CategoryPage data={data} />}
{docType === 'page' && <SinglePage data={data} />} {docType === 'page' && <SinglePage data={data} />}
</> </>
) );
} }
// Background revalidate once every day. // Background revalidate once every day.
export const revalidate = 86400; // export const revalidate = 86400;
/** /**
* Get paths for each page. * Get paths for each page.
*/ */
export async function generateStaticParams() { export async function generateStaticParams() {
const paths = await client.fetch(docQuery) const paths = await client.fetch(docQuery);
return paths.map((path: { return paths.map((path: { slug: string; locale: string }) => ({
slug: string,
locale: string
}) => ({
slug: path.slug.split('/').filter((p) => p), slug: path.slug.split('/').filter((p) => p),
locale: path.locale locale: path.locale
})) }));
} }
/** /**
@ -83,54 +68,51 @@ export async function generateStaticParams() {
* If we're in "preview mode" and have multiple documents, return the draft * If we're in "preview mode" and have multiple documents, return the draft
*/ */
function filterDataToSingleItem(data: any, preview = false) { function filterDataToSingleItem(data: any, preview = false) {
if (!Array.isArray(data)) { if (!Array.isArray(data)) {
return data return data;
} }
if (data.length === 1) { if (data.length === 1) {
return data[0] return data[0];
} }
if (preview) { if (preview) {
return data.find((item) => item._id.startsWith(`drafts.`)) || data[0] return data.find((item) => item._id.startsWith(`drafts.`)) || data[0];
} }
return data[0] return data[0];
} }
/** /**
* Generate metadata for each page. * Generate metadata for each page.
*/ */
export async function generateMetadata({ params }: {params: { slug: string[], locale: string }}): Promise<Metadata> { export async function generateMetadata({
const { slug, locale } = params params
}: {
params: { slug: string[]; locale: string };
}): Promise<Metadata> {
const { slug, locale } = params;
const { query = '', queryParams } = getQueryFromSlug(slug, locale) const { query = '', queryParams } = getQueryFromSlug(slug, locale);
const pageData = await client.fetch(query, queryParams) const pageData = await client.fetch(query, queryParams);
const data = filterDataToSingleItem(pageData, false) const data = filterDataToSingleItem(pageData, false);
const { seo } = data ?? {}; const { seo } = data ?? {};
return { return {
title: seo?.title ? seo?.title : data?.title, title: seo?.title ? seo?.title : data?.title,
description: seo?.description description: seo?.description ? seo.description : 'Webb och digitalbyrå från Göteborg',
? seo.description
: 'Webb och digitalbyrå från Göteborg',
openGraph: { openGraph: {
images: [ images: [
{ {
url: seo?.image?.asset?.url url: seo?.image?.asset?.url ? seo.image.asset.url : '/og-image.jpg',
? seo.image.asset.url
: '/og-image.jpg',
width: 1200, width: 1200,
height: 630, height: 630,
alt: seo?.coverImage?.alt alt: seo?.coverImage?.alt ? seo.coverImage.alt : 'Kodamera AB'
? seo.coverImage.alt }
: 'Kodamera AB', ]
}, }
], };
}, }
}
}

View File

@ -23,53 +23,54 @@
"*": "prettier --write --ignore-unknown" "*": "prettier --write --ignore-unknown"
}, },
"dependencies": { "dependencies": {
"@headlessui/react": "^1.7.10", "@headlessui/react": "^1.7.14",
"@next/bundle-analyzer": "^13.3.4", "@next/bundle-analyzer": "^13.4.3",
"@portabletext/react": "^3.0.0", "@portabletext/react": "^3.0.0",
"@radix-ui/react-dropdown-menu": "^2.0.4", "@radix-ui/react-dropdown-menu": "^2.0.4",
"@radix-ui/react-icons": "^1.3.0", "@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-navigation-menu": "^1.1.2", "@radix-ui/react-navigation-menu": "^1.1.2",
"@sanity/icons": "2", "@sanity/icons": "^2.3.1",
"@sanity/image-url": "^1.0.2", "@sanity/image-url": "^1.0.2",
"@sanity/types": "3", "@sanity/types": "^3.11.1",
"@sanity/ui": "1", "@sanity/ui": "^1.3.3",
"@types/styled-components": "^5.1", "@sanity/webhook": "^2.0.0",
"@types/styled-components": "^5.1.26",
"@vercel/og": "^0.1.0", "@vercel/og": "^0.1.0",
"class-variance-authority": "^0.6.0", "class-variance-authority": "^0.6.0",
"clsx": "^1.2.1", "clsx": "^1.2.1",
"framer-motion": "^8.4.0", "framer-motion": "^8.5.5",
"is-empty-iterable": "^3.0.0", "is-empty-iterable": "^3.0.0",
"lucide-react": "^0.194.0", "lucide-react": "^0.194.0",
"next": "13.4.3", "next": "13.4.3",
"next-intl": "^2.13.1", "next-intl": "^2.14.6",
"next-sanity": "^4.2.0", "next-sanity": "^4.3.2",
"react": "18.2.0", "react": "18.2.0",
"react-cookie": "^4.1.1", "react-cookie": "^4.1.1",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-glider": "^4.0.2", "react-glider": "^4.0.2",
"sanity": "3", "sanity": "^3.11.1",
"styled-components": "^5.2", "styled-components": "^5.3.10",
"tailwind-merge": "^1.12.0", "tailwind-merge": "^1.12.0",
"tailwindcss-animate": "^1.0.5" "tailwindcss-animate": "^1.0.5"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.31.2", "@playwright/test": "^1.34.1",
"@tailwindcss/typography": "^0.5.9", "@tailwindcss/typography": "^0.5.9",
"@types/negotiator": "^0.6.1", "@types/negotiator": "^0.6.1",
"@types/node": "18.13.0", "@types/node": "18.13.0",
"@types/react": "18.0.27", "@types/react": "18.0.27",
"@types/react-dom": "18.0.10", "@types/react-dom": "18.0.10",
"@vercel/git-hooks": "^1.0.0", "@vercel/git-hooks": "^1.0.0",
"autoprefixer": "^10.4.13", "autoprefixer": "^10.4.14",
"eslint": "^8.35.0", "eslint": "^8.41.0",
"eslint-config-next": "^13.4.0", "eslint-config-next": "^13.4.3",
"eslint-config-prettier": "^8.6.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-unicorn": "^45.0.2", "eslint-plugin-unicorn": "^45.0.2",
"lint-staged": "^13.1.1", "lint-staged": "^13.2.2",
"postcss": "^8.4.21", "postcss": "^8.4.23",
"prettier": "^2.8.7", "prettier": "^2.8.8",
"prettier-plugin-tailwindcss": "^0.2.7", "prettier-plugin-tailwindcss": "^0.2.8",
"tailwindcss": "^3.2.6", "tailwindcss": "^3.3.2",
"typescript": "4.9.5" "typescript": "4.9.5"
} }
} }

43
pages/api/revalidate.ts Normal file
View File

@ -0,0 +1,43 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { isValidSignature, SIGNATURE_HEADER_NAME } from '@sanity/webhook';
const SANITY_WEBHOOK_SECRET = `${process.env.SANITY_WEBHOOK_SECRET}`;
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const signature = `${req.headers[SIGNATURE_HEADER_NAME]}`;
const isValid = isValidSignature(JSON.stringify(req.body), signature, SANITY_WEBHOOK_SECRET);
console.log(`===== Is the webhook request valid? ${isValid}`);
// Validate signature
if (!isValid) {
res.status(401).json({ success: false, message: 'Invalid signature' });
return;
}
const slug = req.body.slug;
const locale = req.body.locale;
const type = req.body._type;
let pathToRevalidate = "";
switch(type) {
case "home":
pathToRevalidate = `${slug}${locale}`;
break;
default:
break;
}
console.log(`Path to revalidate: ${pathToRevalidate}`)
try {
await res.revalidate(`${pathToRevalidate}`);
return res.json({ revalidated: true });
} catch (err) {
// Could not revalidate. The stale page will continue to be shown until
// this issue is fixed.
return res.status(500).send('Error while revalidating');
}
}

1310
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff