From 2d40a3d060dd451435a7a8e3a3ecf6f757e56520 Mon Sep 17 00:00:00 2001 From: Ben Zhang Date: Sat, 12 Oct 2024 20:50:15 -0700 Subject: [PATCH] Serve static assets using dev server during development (#8) A bug was introduced in #7 where WATcloudURI-based images can't be loaded in the development environment. This PR fixes this. Before: image After: image --- .gitignore | 4 +++- package.json | 2 +- utils/watcloud-uri.ts | 31 +++++++++++++++++++++++++++++-- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 7fc5c30..fe4e097 100644 --- a/.gitignore +++ b/.gitignore @@ -143,4 +143,6 @@ dist # End of https://www.toptal.com/developers/gitignore/api/node -/.react-email \ No newline at end of file +/.react-email +# For storing development cache +/emails/static/cache \ No newline at end of file diff --git a/package.json b/package.json index 979c4d7..d2e489e 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dist" ], "scripts": { - "dev": "concurrently --kill-others \"email dev\" \"tsc -w\"", + "dev": "NODE_ENV=development concurrently --kill-others \"email dev\" \"tsc -w\"", "build": "tsc", "prepack": "npm run build" }, diff --git a/utils/watcloud-uri.ts b/utils/watcloud-uri.ts index d33f1db..e585c69 100644 --- a/utils/watcloud-uri.ts +++ b/utils/watcloud-uri.ts @@ -58,9 +58,36 @@ export class WATcloudURI extends URL { } resolveFromCache() { - const ret = assetCache.get(this.sha256); + let ret = assetCache.get(this.sha256); if (!ret) { - throw new Error(`Asset ${this.sha256} not found in the cache.`); + // If we are in development mode, serve the asset using the dev server + if (process.env.NODE_ENV === "development") { + const fs = require('fs'); + const path = require('path'); + const { Readable } = require('stream'); + + const staticCachePath = path.resolve(__dirname, "../emails/static/cache"); + const filename = this.sha256; + const filepath = path.join(staticCachePath, filename); + + if (!fs.existsSync(filepath)) { + if (!fs.existsSync(staticCachePath)) { + fs.mkdirSync(staticCachePath, { recursive: true }); + } + this.resolveToURL().then((url) => { + fetch(url).then((res) => { + const dest = fs.createWriteStream(filepath); + if (res.body) { + Readable.from(res.body).pipe(dest); + } + }) + }) + } + + ret = `${process.env.CDN_URL || ""}/static/cache/${filename}`; + } else { + throw new Error(`Asset ${this.sha256} not found in the cache.`); + } } return ret