From 94130b62b6b5b9aa7e6d2a7f8ff6bdf43101c838 Mon Sep 17 00:00:00 2001 From: Graeme Fulton Date: Thu, 20 Jun 2024 15:06:59 -0400 Subject: [PATCH] clear cache with cloudflare worker --- lib/utils/cloudflare.js | 64 +++++++++++++++++++++++++++-------------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/lib/utils/cloudflare.js b/lib/utils/cloudflare.js index e93c801b..4c884168 100644 --- a/lib/utils/cloudflare.js +++ b/lib/utils/cloudflare.js @@ -1,24 +1,44 @@ -import axios from 'axios' -export const purgeCloudFlareCache = async(url) =>{ - try { - const response = await axios.post( - `https://api.cloudflare.com/client/v4/zones/${process.env.CLOUDFLARE_API_ZONE}/purge_cache`, - { files: [`${process.env.NEXT_PUBLIC_HOME_URL}${url}`] }, - { - headers: { - 'Authorization': `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`, - 'Content-Type': 'application/json' - } - } - ); - - if (response.data.success) { - return true - // res.status(200).json({ message: 'Cache purged successfully' }); - } else { - console.log('Cloudflare cache purge failed', response.data) +import axios from "axios"; +export const purgeCloudFlareCache = async url => { + try { + const response = await axios.post( + `https://api.cloudflare.com/client/v4/zones/${process.env.CLOUDFLARE_API_ZONE}/purge_cache`, + { files: [`${process.env.NEXT_PUBLIC_HOME_URL}${url}`] }, + { + headers: { + Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`, + "Content-Type": "application/json", + }, } - } catch (error) { - console.log('Cloudflare cache purge failed', error) + ); + + if (response.data.success) { + return true; + // res.status(200).json({ message: 'Cache purged successfully' }); + } else { + console.log("Cloudflare cache purge failed", response.data); } - } \ No newline at end of file + clearWorkerCache(url); + } catch (error) { + console.log("Cloudflare cache purge failed", error); + } +}; + +const clearWorkerCache = async path => { + const workerURL = `${process.env.NEXT_PUBLIC_HOME_URL}/clear-cache?path=${encodeURIComponent(path)}`; + + try { + const response = await fetch(workerURL, { + method: "GET", + }); + + if (!response.ok) { + throw new Error("Failed to clear cache"); + } + + const result = await response.text(); + res.status(200).json({ message: result }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +};