Skip to content

Commit

Permalink
Serve static assets using dev server during development (#8)
Browse files Browse the repository at this point in the history
A bug was introduced in #7 where WATcloudURI-based images can't be
loaded in the development environment. This PR fixes this.

Before:
<img width="1392" alt="image"
src="https://github.com/user-attachments/assets/f0833cc8-cfe2-485d-b697-3e2226578de2">


After:

<img width="1392" alt="image"
src="https://github.com/user-attachments/assets/a3082519-e9c3-4a75-91d1-0fbb9b78bea7">
  • Loading branch information
ben-z authored Oct 13, 2024
1 parent 3472e64 commit 2d40a3d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,6 @@ dist

# End of https://www.toptal.com/developers/gitignore/api/node

/.react-email
/.react-email
# For storing development cache
/emails/static/cache
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
31 changes: 29 additions & 2 deletions utils/watcloud-uri.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 2d40a3d

Please sign in to comment.