Skip to content

Commit

Permalink
Add MongoDB
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillweston committed Apr 20, 2024
1 parent dd38a68 commit baed6a2
Show file tree
Hide file tree
Showing 5 changed files with 269 additions and 33 deletions.
148 changes: 148 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"express": "^4.19.2",
"fs": "^0.0.1-security",
"https": "^1.0.0",
"mongodb": "^6.5.0",
"multer": "^1.4.5-lts.1",
"path": "^0.12.7"
}
Expand Down
37 changes: 37 additions & 0 deletions src/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const { MongoClient } = require('mongodb');

if (!process.env.DOCKER_ENV) {
require('dotenv').config();
}

// Construct the MongoDB URI using environment variables
const uri = `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}`
+ `@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/?authSource=admin`;

const client = new MongoClient(uri);
let dbConnection = null;

module.exports = {
connectToServer() {
return new Promise((resolve, reject) => {
client.connect()
.then(() => {
console.log("Connected successfully to MongoDB server");
// Connect to the log database
dbConnection = client.db(process.env.MONGODB_DB);
resolve({ dbConnection });
})
.catch((err) => {
console.error("Failed to connect to MongoDB server:", err);
reject(err);
});
});
},
getDb() {
return dbConnection;
},
closeConnection() {
console.log("Closing connection to MongoDB server");
client.close();
},
};
78 changes: 78 additions & 0 deletions src/function.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
const mongoUtil = require('./db');

let dbConnection = null;

mongoUtil.connectToServer()
.then(({ dbConnection: localDbConnection }) => {
console.log("Successfully connected to MongoDB.");

// Create a unique index for 'userId'
localDbConnection.collection('imageUpload').createIndex({ userId: 1 }, { unique: true })
.then(() => console.log("Unique index created successfully on 'userId'"))
.catch(err => console.error("Error creating unique index on 'userId':", err));

// Create a compound index for 'fileName' and 'createdAt' without enforcing uniqueness
localDbConnection.collection('imageUpload').createIndex({ userId: 1, fileName: 1, createdAt: -1 }, { unique: false })
.then(() => console.log("Index created successfully on 'fileName' and 'createdAt'"))
.catch(err => console.error("Error creating index on 'fileName' and 'createdAt':", err));

// Assign the database connections to the variables declared at higher scope
dbConnection = localDbConnection;
})
.catch(err => {
console.error("Failed to connect to MongoDB:", err);
});

// Authenticate with B2
async function authenticateB2() {
try {
await b2.authorize();
} catch (error) {
console.error('B2 Authorization error:', error);
throw error;
}
}

// Upload file to B2
async function uploadToB2(filePath, fileName) {
try {
await authenticateB2();
const uploadUrl = await b2.getUploadUrl({
bucketId: process.env.B2_BUCKET_ID
});

const response = await b2.uploadFile({
uploadUrl: uploadUrl.data.uploadUrl,
uploadAuthToken: uploadUrl.data.authorizationToken,
filename: fileName,
data: Buffer.from(require('fs').readFileSync(filePath))
});

return response.data;
} catch (error) {
console.error('B2 upload error:', error);
throw error;
}
}

async function logUploadDetails(userId, fileName) {
try {
const collection = dbConnection.collection('imageUpload');

const logEntry = {
userId: userId,
fileName: fileName,
createdAt: new Date() // Record the current timestamp
};

await collection.insertOne(logEntry);
console.log('Upload logged successfully:', logEntry);
} catch (error) {
console.error('Error logging upload to MongoDB:', error);
}
}

module.exports = {
uploadToB2,
logUploadDetails
};
38 changes: 5 additions & 33 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const path = require('path');
const B2 = require('backblaze-b2');
const https = require('https');
const fs = require('fs');
const utils = require('./function');

if (!process.env.DOCKER_ENV) {
require('dotenv').config();
Expand Down Expand Up @@ -34,38 +35,6 @@ const storage = multer.diskStorage({

const upload = multer({ storage: storage });

// Authenticate with B2
async function authenticateB2() {
try {
await b2.authorize();
} catch (error) {
console.error('B2 Authorization error:', error);
throw error;
}
}

// Upload file to B2
async function uploadToB2(filePath, fileName) {
try {
await authenticateB2();
const uploadUrl = await b2.getUploadUrl({
bucketId: process.env.B2_BUCKET_ID
});

const response = await b2.uploadFile({
uploadUrl: uploadUrl.data.uploadUrl,
uploadAuthToken: uploadUrl.data.authorizationToken,
filename: fileName,
data: Buffer.from(require('fs').readFileSync(filePath))
});

return response.data;
} catch (error) {
console.error('B2 upload error:', error);
throw error;
}
}

// Endpoint to handle POST requests for file uploads
app.post('/upload', upload.single('image'), async (req, res) => {
const userId = req.body.userId; // Retrieve the userId from form data
Expand All @@ -79,7 +48,10 @@ app.post('/upload', upload.single('image'), async (req, res) => {
const localFileName = req.file.filename;

// Upload to Backblaze B2
const b2Response = await uploadToB2(localFilePath, localFileName);
const b2Response = await utils.uploadToB2(localFilePath, localFileName);

// Log the upload details in MongoDB
await utils.logUploadDetails(userId, localFileName);

// Send success response
res.send({
Expand Down

0 comments on commit baed6a2

Please sign in to comment.