Refactored - now includes fullstack AUTH
This commit is contained in:
20
server/utils/app.js
Normal file
20
server/utils/app.js
Normal file
@@ -0,0 +1,20 @@
|
||||
const express = require('express') // Backend App (server)
|
||||
const cors = require('cors') // HTTP headers (enable requests)
|
||||
const {ORIGIN} = require('../constants')
|
||||
|
||||
// initialize app
|
||||
const app = express()
|
||||
|
||||
// middlewares
|
||||
app.use(cors({origin: ORIGIN}))
|
||||
app.use(express.json({extended: true})) // body parser
|
||||
app.use(express.urlencoded({extended: false})) // url parser
|
||||
|
||||
// error handling
|
||||
app.use((err, req, res, next) => {
|
||||
console.error(err)
|
||||
res.status(500).send()
|
||||
next()
|
||||
})
|
||||
|
||||
module.exports = app
|
||||
32
server/utils/mongo.js
Normal file
32
server/utils/mongo.js
Normal file
@@ -0,0 +1,32 @@
|
||||
const mongoose = require('mongoose')
|
||||
const {MONGO_URI} = require('../constants')
|
||||
const {MONGO_OPTIONS} = require('../constants')
|
||||
|
||||
class MongoDB {
|
||||
constructor() {
|
||||
this.mongoose = mongoose
|
||||
this.isConnected = false
|
||||
this.MONGO_URI = MONGO_URI
|
||||
this.MONGO_OPTIONS = MONGO_OPTIONS
|
||||
}
|
||||
|
||||
async connect() {
|
||||
if (this.isConnected) return
|
||||
|
||||
try {
|
||||
const db = await this.mongoose.connect(this.MONGO_URI, this.MONGO_OPTIONS)
|
||||
const connection = db.connection
|
||||
|
||||
this.isConnected = connection.readyState === 1
|
||||
if (this.isConnected) console.log('✅ MongoDB connected')
|
||||
|
||||
connection.on('connected', () => console.log('✅ MongoDB connected')) // re-connected
|
||||
connection.on('disconnected', () => console.log('❌ MongoDB disconnected')) // disconnected
|
||||
connection.on('error', (error) => console.log('❌ MongoDB connection error', error)) // listen for errors during the session
|
||||
} catch (error) {
|
||||
console.log('❌ MongoDB connection error:', error.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MongoDB()
|
||||
Reference in New Issue
Block a user