2024-03-29 20:08:34 -04:00
|
|
|
const { ObjectId } = require('mongodb');
|
|
|
|
|
|
|
|
|
|
class Images {
|
|
|
|
|
|
2024-10-02 10:23:56 -04:00
|
|
|
constructor(db) {
|
|
|
|
|
this.db = db;
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
async upload(file, userId) {
|
2025-01-11 00:03:05 -05:00
|
|
|
await this.db.connect()
|
|
|
|
|
const conn = this.db.getConnection();
|
2024-03-29 20:08:34 -04:00
|
|
|
|
|
|
|
|
const imagesCollection = conn.collection('images');
|
|
|
|
|
|
|
|
|
|
const newImage = {
|
|
|
|
|
userId: userId,
|
|
|
|
|
file_name: file.originalname,
|
|
|
|
|
file_content: file.buffer.toString('base64'),
|
|
|
|
|
mime_type: file.mimetype,
|
|
|
|
|
created_at: new Date()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const result = await imagesCollection.insertOne(newImage);
|
|
|
|
|
|
|
|
|
|
return result.insertedId;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async get(id) {
|
2025-01-11 00:03:05 -05:00
|
|
|
await this.db.connect()
|
|
|
|
|
const conn = this.db.getConnection();
|
2024-03-29 20:08:34 -04:00
|
|
|
|
|
|
|
|
const imagesCollection = conn.collection('images');
|
|
|
|
|
|
2024-10-03 12:05:20 -04:00
|
|
|
const result = await imagesCollection.findOne({ _id: ObjectId.createFromHexString(id) });
|
2024-03-29 20:08:34 -04:00
|
|
|
|
|
|
|
|
if (!result) return null;
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
file_name: result.file_name,
|
|
|
|
|
file_content: Buffer.from(result.file_content, 'base64'),
|
|
|
|
|
mime_type: result.mime_type
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-22 17:56:53 -05:00
|
|
|
//TODO TEST
|
|
|
|
|
async getAll() {
|
|
|
|
|
await this.db.connect()
|
|
|
|
|
const conn = this.db.getConnection();
|
|
|
|
|
|
|
|
|
|
const imagesCollection = conn.collection('images');
|
|
|
|
|
|
|
|
|
|
const result = await imagesCollection.find({});
|
|
|
|
|
|
|
|
|
|
if (!result) return null;
|
|
|
|
|
|
|
|
|
|
//TODO latency issues -> images > 20
|
2025-02-22 18:08:38 -05:00
|
|
|
// USE pagination
|
|
|
|
|
/*
|
|
|
|
|
app.get('/images', (req, res) => {
|
|
|
|
|
const page = parseInt(req.query.page) || 1;
|
|
|
|
|
const limit = parseInt(req.query.limit) || 10;
|
|
|
|
|
|
|
|
|
|
const images = getImagesFromDatabase(page, limit);
|
|
|
|
|
res.json(images);
|
|
|
|
|
});
|
|
|
|
|
*/
|
2025-02-22 17:56:53 -05:00
|
|
|
const imagesName = result.map(image => ({
|
|
|
|
|
id: image.id,
|
|
|
|
|
file_name: image.file_name,
|
|
|
|
|
file_content: Buffer.from(image.file_content, 'base64'),
|
|
|
|
|
mime_type: image.mime_type
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
return imagesName;
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
|
|
|
|
|
2024-10-02 10:23:56 -04:00
|
|
|
module.exports = Images;
|