Skip to content

Commit

Permalink
feat: Add image service for cat images
Browse files Browse the repository at this point in the history
  • Loading branch information
aridanemartin committed Nov 30, 2024
1 parent 9a481d9 commit b7478e4
Show file tree
Hide file tree
Showing 10 changed files with 2,059 additions and 290 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
init.sql
node_modules
.env
17 changes: 16 additions & 1 deletion controllers/CatController.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ export class CatController {
getById = async (req, res) => {
try {
const { id } = req.params;
const response = await this.catModel.getById(id);
const response = await this.catModel.getById(id);
if (response) res.status(200).json(response);


else res.status(404).json({ error: 'Cat not found' });
} catch (error) {
console.error(error);
Expand Down Expand Up @@ -65,11 +67,24 @@ export class CatController {
}
};

getImageById = async (req, res) => {
try {
const { id } = req.params;
const data = await this.catModel.getImage(id);

res.status(200).json(data);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

uploadImage = async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}

const { id } = req.params;
const response = await this.catModel.uploadImage(req, id);
if (response) res.status(200).json(response);
Expand Down
7 changes: 4 additions & 3 deletions db/config.development.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export const config = {
host: process.env.DB_HOST, // Name of docker Service instead of 'localhost'
user: 'root',
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: 'gatos_sin_hogar'
database: process.env.DB_NAME,
port: process.env.DB_PORT || 3306
};
1 change: 1 addition & 0 deletions db/db_connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import mysql from 'mysql2/promise';
import { logEnvironment } from '../utils/logger.js';

const env = process.env.NODE_ENV || 'development';

let db;

try {
Expand Down
82 changes: 61 additions & 21 deletions models/cat.model.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import db from '../db/db_connection.js';
import AWS from 'aws-sdk';
import {
uploadImage,
getImage,
deleteImage
} from '../services/imageService.js';

const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
});
export class CatModel {
static async getAll(req) {
try {
Expand All @@ -19,6 +18,13 @@ export class CatModel {
const dataQuery = `SELECT * FROM cat LIMIT ${itemsPerPage} OFFSET ${offset}`;
const cats = await db.query(dataQuery);

const catIds = cats[0].map((cat) => cat.id);
const catPictures = await CatModel.getImages(catIds);

for (const cat of cats[0]) {
cat.picture = catPictures[cat.id] || null;
}

const result = {
data: cats[0],
pagination: {
Expand All @@ -39,6 +45,12 @@ export class CatModel {
static async getById(id) {
try {
const cat = await db.query('SELECT * FROM cat WHERE id = ?', [id]);

if (cat[0][0].picture) {
const catPicture = await getImage(id);
cat[0][0].picture = catPicture;
}

return cat[0][0];
} catch (error) {
console.error('Error fetching cat:', error);
Expand Down Expand Up @@ -155,30 +167,58 @@ export class CatModel {

static async uploadImage(req, id) {
try {
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: `images/${id}`,
Body: req.file.buffer,
ContentType: req.file.mimetype
};
const data = await s3.upload(params).promise();
return data;
const imageUrl = await uploadImage(req.file, id);
return { imageUrl };
} catch (error) {
console.error(error);
throw error;
}
}

static async getImage(id) {
try {
const cat = await db.query('SELECT picture FROM cat WHERE id = ?', [
id
]);
if (!cat[0][0] || !cat[0][0].picture) {
return null;
}

const r2ImageSignedUrl = await getImage(id);
return r2ImageSignedUrl;
} catch (error) {
throw error;
}
}

static async getImages(ids) {
const placeholders = ids.map(() => '?').join(',');
const query = `SELECT id, picture FROM cat WHERE id IN (${placeholders})`;
const cats = await db.query(query, ids);

const imageUrls = {};
for (const cat of cats[0]) {
if (cat.picture) {
try {
const r2ImageSignedUrl = await getImage(cat.id);
imageUrls[cat.id] = r2ImageSignedUrl;
} catch (error) {
console.error(
`Error fetching image for cat ${cat.id}:`,
error
);
}
}
}

return imageUrls;
}

static async deleteImage(id) {
try {
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: `images/${id}`
};
const data = await s3.deleteObject(params).promise();
const data = await deleteImage(id);
return data;
} catch (error) {
console.error(error);
console.error('Error deleting image:', error);
throw error;
}
}
Expand Down
Loading

0 comments on commit b7478e4

Please sign in to comment.