From 70a3e1895b5a066258a9d08974960d580cbe578d Mon Sep 17 00:00:00 2001 From: DrMint Date: Mon, 28 Mar 2022 18:04:47 +0200 Subject: [PATCH] Added On-demand revalidation --- src/pages/api/revalidate.ts | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/pages/api/revalidate.ts diff --git a/src/pages/api/revalidate.ts b/src/pages/api/revalidate.ts new file mode 100644 index 0000000..7199995 --- /dev/null +++ b/src/pages/api/revalidate.ts @@ -0,0 +1,50 @@ +import type { NextApiRequest, NextApiResponse } from "next"; + +export type RequestMailProps = { + event: "entry.update" | "entry.delete" | "entry.create"; + model: string; + entry: { + slug: string; + }; +}; + +export type ResponseMailProps = { + message: string; + revalidated: boolean; +}; + +export default async function Mail( + req: NextApiRequest, + res: NextApiResponse +) { + console.log(req.body); + const body = req.body as RequestMailProps; + + // Check for secret to confirm this is a valid request + if ( + req.headers.authorization !== `Bearer ${process.env.REVALIDATION_TOKEN}` + ) { + return res + .status(401) + .json({ message: "Invalid token", revalidated: false }); + } + + const uRLsToRevalidate: string[] = []; + + if (body.model === "post") { + uRLsToRevalidate.push(`/news/${body.entry.slug}`); + } + + console.table(uRLsToRevalidate); + + try { + uRLsToRevalidate.map(async (url) => await res.unstable_revalidate(url)); + return res.json({ message: "Success!", revalidated: true }); + } catch (err) { + // If there was an error, Next.js will continue + // to show the last successfully generated page + return res + .status(500) + .send({ message: "Error revalidating", revalidated: false }); + } +}