removed unused endpoints from index.js, moved db connection to index.js

This commit is contained in:
Alex Holliday
2024-10-24 12:31:22 +08:00
parent 07a918b70c
commit 0649002d27
3 changed files with 36 additions and 67 deletions

View File

@@ -1,15 +0,0 @@
const PORT = 5000;
const connectDbAndRunServer = async (app, db) => {
try {
await db.connect();
app.listen(PORT, () => {
console.log(`server started on port:${PORT}`);
});
} catch (error) {
console.log("Failed to connect to DB");
console.error(error);
}
};
export { connectDbAndRunServer };

View File

@@ -1,6 +1,8 @@
import mongoose from "mongoose";
import UserModel from "../models/User.js";
import AppSettings from "../models/AppSettings.js";
import logger from "../../utils/logger.js";
const SERVICE_NAME = "MongoDB";
//****************************************
// DB Connection
@@ -17,14 +19,30 @@ const connect = async () => {
appSettings = new AppSettings({});
await appSettings.save();
}
console.log("Connected to MongoDB");
logger.info("Connected to MongoDB", { service: SERVICE_NAME, method: "connect" });
} catch (error) {
console.error("Failed to connect to MongoDB");
logger.error("failed to connect to MongoDB", {
service: SERVICE_NAME,
method: "connect",
});
throw error;
}
};
const disconnect = async () => {
try {
logger.info("Disconnecting from MongoDB", { service: SERVICE_NAME });
await mongoose.disconnect();
logger.info("Disconnected from MongoDB", { service: SERVICE_NAME });
return;
} catch (error) {
logger.error("failed to disconnect from MongoDB", {
service: SERVICE_NAME,
errorMsg: error.message,
});
}
};
const checkSuperadmin = async (req, res) => {
try {
const superAdmin = await UserModel.findOne({ role: "superadmin" });
@@ -148,6 +166,7 @@ import { getAppSettings, updateAppSettings } from "./modules/settingsModule.js";
export default {
connect,
disconnect,
insertUser,
getUserByEmail,
updateUser,

View File

@@ -17,7 +17,6 @@ import maintenanceWindowRouter from "./routes/maintenanceWindowRoute.js";
import settingsRouter from "./routes/settingsRoute.js";
import { fileURLToPath } from "url";
import { connectDbAndRunServer } from "./configs/db.js";
import queueRouter from "./routes/queueRoute.js";
//JobQueue service and dependencies
@@ -51,31 +50,11 @@ const __dirname = path.dirname(__filename);
const openApiSpec = JSON.parse(
fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8")
);
const PORT = 5000;
// Need to wrap server setup in a function to handle async nature of JobQueue
const startApp = async () => {
// **************************
// Here is where we can swap out DBs easily. Spin up a mongoDB instance and try it out.
// Simply comment out the FakeDB and uncomment the MongoDB or vice versa.
// We can easily swap between any type of data source as long as the methods are implemented
//
// FakeDB
// const db = require("./db/FakeDb");
//
// MongoDB
// const db = require("./db/MongoDB");
//
// **************************
// const DB_TYPE = {
// MongoDB: async () => (await import("./db/mongo/MongoDB.js")).default,
// FakedDB: async () => (await import("./db/FakeDb.js")).default,
// };
// const db = DB_TYPE[process.env.DB_TYPE]
// ? DB_TYPE[process.env.DB_TYPE]()
// : require("./db/FakeDb");
// const db = DB_TYPE.MongoDB();
const app = express();
// middlewares
@@ -85,12 +64,8 @@ const startApp = async () => {
);
app.use(express.json());
app.use(helmet());
// **************************
// Make DB accessible anywhere we have a Request object
// By adding the DB to the request object, we can access it in any route
// Thus we do not need to import it in every route file, and we can easily swap out DBs as there is only one place to change it
// Same applies for JobQueue and emailService
// **************************
// Add db, jobQueue, emailService, and settingsService to request object for easy access
app.use((req, res, next) => {
req.db = db;
req.jobQueue = jobQueue;
@@ -122,23 +97,6 @@ const startApp = async () => {
}
});
app.use("/api/v1/mail", async (req, res) => {
try {
const id = await req.emailService.buildAndSendEmail(
"welcomeEmailTemplate",
{
name: "Alex",
},
"ajhollid@gmail.com",
"Welcome"
);
res.status(200).json({ success: true, msg: "Email sent", data: id });
} catch (error) {
logger.error(error.message);
return res.status(500).json({ message: error.message });
}
});
/**
* Error handler middleware
* Should be called last
@@ -146,7 +104,10 @@ const startApp = async () => {
app.use(handleErrors);
// Create services
await connectDbAndRunServer(app, db);
await db.connect();
app.listen(PORT, () => {
console.log(`server started on port:${PORT}`);
});
const settingsService = new SettingsService(AppSettings);
await settingsService.loadSettings();
@@ -178,6 +139,7 @@ const startApp = async () => {
try {
console.log("Shutting down gracefully");
await jobQueue.obliterate();
await db.disconnect();
console.log("Finished cleanup");
} catch (error) {
logger.error(errorMessages.JOB_QUEUE_DELETE_JOB, {
@@ -193,5 +155,8 @@ const startApp = async () => {
};
startApp().catch((error) => {
console.log(error);
logger.error(error.message, {
service: SERVICE_NAME,
});
process.exit(1);
});