Skip to content

Commit

Permalink
feat: Implement image cache in imageService
Browse files Browse the repository at this point in the history
  • Loading branch information
aridanemartin committed Nov 30, 2024
1 parent b7478e4 commit 610f804
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
22 changes: 21 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"cors": "^2.8.5",
"express": "^4.18.2",
"multer": "^1.4.5-lts.1",
"mysql2": "^3.6.1"
"mysql2": "^3.6.1",
"node-cache": "^5.1.2"
},
"devDependencies": {
"@types/node": "^22.10.1",
Expand Down
15 changes: 15 additions & 0 deletions services/imageService.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import {
DeleteObjectCommand
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import NodeCache from 'node-cache';
import r2 from './s3client/s3client.js';

// Create a cache instance with a default TTL (time-to-live) of 1 hour
const imageCache = new NodeCache({ stdTTL: 3600 });

export const uploadImage = async (file, id) => {
const buffer = file.buffer;

Expand All @@ -19,13 +23,20 @@ export const uploadImage = async (file, id) => {
try {
await r2.send(putObjectCommand);
const imageUrl = `${process.env.CLOUDFARE_ENDPOINT}/${process.env.CLOUDFARE_BUCKET_NAME}/images/${id}`;

imageCache.set(id, imageUrl);
return imageUrl;
} catch (error) {
throw error;
}
};

export const getImage = async (id) => {
const cachedImageUrl = imageCache.get(id);
if (cachedImageUrl) {
return cachedImageUrl;
}

const getObjectCommand = new GetObjectCommand({
Bucket: process.env.CLOUDFARE_BUCKET_NAME,
Key: `images/${id}`
Expand All @@ -35,6 +46,8 @@ export const getImage = async (id) => {
const r2ImageSignedUrl = await getSignedUrl(r2, getObjectCommand, {
expiresIn: 60 * 60
});

imageCache.set(id, r2ImageSignedUrl);
return r2ImageSignedUrl;
} catch (error) {
throw error;
Expand All @@ -49,6 +62,8 @@ export const deleteImage = async (id) => {

try {
const data = await r2.send(deleteObjectCommand);

imageCache.del(id);
return data;
} catch (error) {
throw error;
Expand Down

0 comments on commit 610f804

Please sign in to comment.