Skip to content

Commit

Permalink
Add image render caching
Browse files Browse the repository at this point in the history
  • Loading branch information
constantgillet committed Apr 25, 2024
1 parent 14f8c90 commit 058eb34
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
8 changes: 5 additions & 3 deletions app/libs/s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ export const multipleDeleteFromS3 = async (keys: string[]) => {
}
};

/**
* Check if a file exists in S3
* @param filePath ex "ogimages/generated/test.png"
* @returns
*/
export const fileExists = async (filePath: string) => {
const command = new HeadObjectCommand({
Bucket: "cgbucket",
Expand All @@ -96,14 +101,11 @@ export const fileExists = async (filePath: string) => {

try {
await s3.send(command);
console.log(`File exists: ${filePath}`);
return { exists: true, error: null };
} catch (error) {
if (error.name === "NotFound") {
console.log(`File does not exist: ${filePath}`);
return { exists: false, error: null };
}
console.error(`Error checking file existence: ${error}`);
return { exists: false, error };
}
};
26 changes: 26 additions & 0 deletions app/routes/api.render.$templateId.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Resvg } from "@resvg/resvg-js";
import CryptoJS from "crypto-js";
import { getCacheData, setCacheData } from "~/libs/redis.server";
import { SvgGenerate } from "~/utils/svgGenerate";
import { fileExists, uploadToS3 } from "~/libs/s3";

const cacheEnabled = true;

Expand Down Expand Up @@ -38,6 +39,28 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {
variablesValues.push({ name: key, value });
});

//create a hash of the params
const templateIdHashed = CryptoJS.SHA256(templateId).toString();
const variablesValuesHashed = CryptoJS.SHA256(
JSON.stringify(variablesValues)
).toString();

const cacheKey = `og-image-render-${templateIdHashed}-${variablesValuesHashed}`;

const imageLocation = `ogimages/cached/${cacheKey}.png`;

const resFileExists = await fileExists(imageLocation);

//If the exit 307 the image is cached
if (resFileExists.exists) {
return new Response(null, {
status: 307,
headers: {
Location: `${bucketURL}/${imageLocation}`,
},
});
}

//Get query params
// const url = new URL(`https://og-image/render/${templateName}`);

Expand Down Expand Up @@ -138,6 +161,9 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {
const pngData = resvg.render();
const pngBuffer = pngData.asPng();

//Save the image to S3 as a cache
uploadToS3(pngBuffer, imageLocation);

return new Response(pngBuffer, {
headers: {
"Content-Type": "image/png",
Expand Down

0 comments on commit 058eb34

Please sign in to comment.