Skip to content

Commit

Permalink
separated the routes ,middlewares & other setups into app.js
Browse files Browse the repository at this point in the history
  • Loading branch information
abhiraj-ku committed Oct 2, 2024
1 parent 207bcea commit 1c86135
Show file tree
Hide file tree
Showing 10 changed files with 118 additions and 109 deletions.
4 changes: 1 addition & 3 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
node_modules
Dockerfile
.dockerignore
node_modules
41 changes: 41 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const express = require("express");
const cookieParser = require("cookie-parser");
const monogoSanitize = require("express-mongo-sanitize");
const morgan = require("morgan");
const connectDB = require("./src/db/db");

// App logic based routes
const userRoute = require("./src/routes/userRoute");
const groupRoute = require("./src/routes/groupRoute");

// Initialize the app
const app = express();

// Connect to the database
connectDB();

// Middleware to parse JSON and urlEncoded
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(monogoSanitize());

// Cookie parser middleware
app.use(cookieParser());

// HTTP request logger middleware
app.use(morgan("tiny"));

// Sample route to test the server
app.get("/home", (req, res) => {
res.status(200).json({
message: "hello visitor!",
});
});

// User route middleware
app.use("/user/new", userRoute);

// Group create and join route middleware
app.use("/handle/g", groupRoute);

module.exports = app;
50 changes: 10 additions & 40 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,29 @@
require("dotenv").config();
const express = require("express");
const app = express();
const PORT = process.env.PORT;
const cookieParser = require("cookie-parser");
const monogoSanitize = require("express-mongo-sanitize");
const app = require("./app");
const {
pollEmailQueue,
pollInviteQueue,
pollBarterNotification,
} = require("./src/services/emailQueueProcessor");

const connectDB = require("./src/db/db");

var morgan = require("morgan");

// call the db connection url
connectDB();

// Middleware to parse json and urlEncoded
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(monogoSanitize());

// cookie parser Middleware
app.use(cookieParser());

// HTTP request logger middleware
app.use(morgan("tiny"));

//sample route to test the server
app.get("/home", (req, res) => {
res.status(200).json({
message: "hello visitor !",
});
});

// user route
const userRoute = require("./src/routes/userRoute");

// user route middleware
app.use("/user/new", userRoute);
const PORT = process.env.PORT;

// poll redis queues
// Start polling the Redis queues
pollEmailQueue();
pollInviteQueue();
pollBarterNotification();

// Start the server
const server = app.listen(PORT, () => {
console.log(`server is running on the port: ${PORT}`);
console.log(`Server is running on port: ${PORT}`);
});

// gracefully close the server (ctrl+c)
// Gracefully close the server on SIGINT (Ctrl+C)
process.on("SIGINT", () => {
console.log(`SIGINT signal recieved, closing the server`);
console.log(`SIGINT signal received, closing the server...`);

server.close(() => {
console.log(`Closed the HTTP server gracefully..`);
console.log(`Closed the HTTP server gracefully.`);
process.exit(1);
});
});
67 changes: 22 additions & 45 deletions package-lock.json

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

7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"redis",
"bill split app",
"docker",
"project"
"project",
"bill-split"
],
"author": "Abhishek Kumar",
"license": "ISC",
Expand All @@ -21,17 +22,15 @@
"axios": "^1.7.4",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"csv-parser": "^3.0.0",
"disposable-email-domains": "^1.0.62",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-mongo-sanitize": "^2.2.0",
"express-rate-limit": "^7.4.0",
"hashi-vault-js": "^0.4.16",
"jimp": "^1.3.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.5.3",
"morgan": "^1.10.0",
"node-cron": "^3.0.3",
"nodemailer": "^6.9.14",
"qrcode": "^1.5.4",
"rate-limit-redis": "^4.2.0",
Expand Down
12 changes: 0 additions & 12 deletions src/models/barterModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,3 @@ barterPaymentsSchema.pre("save", function (next) {
const BarterPayment = mongoose.model("BarterPayment", barterPaymentsSchema);

module.exports = BarterPayment;

/*
debtor: The user who owes the amount and proposes a barter.
creditor: The user who is owed the amount and must approve the barter.
groupId: The group in which the barter payment is being made.
amount: The debt amount that the barter is being proposed for.
barterType: The type of barter (e.g., assignment, groceries) based on the amount.
status: The status of the barter proposal (pending, approved, rejected).
settlementDate: The date when the barter is settled (only set if the barter is approved).
timestamps: Auto-generated fields to track when the barter was created and last updated.
*/
3 changes: 2 additions & 1 deletion src/models/groupModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ const groupSchema = new mongoose.Schema({
],
maxBarterAmount: {
type: Number,
default: 0,
min: 0,
required: true,
},
createdAt: {
type: Date,
Expand Down
5 changes: 5 additions & 0 deletions src/models/userModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ const userSchema = new mongoose.Schema({
ref: "Event",
},
],
rislApetite: {
type: Number,
required: true,
min: 0,
},
preferences: {
notifications: {
type: Boolean,
Expand Down
23 changes: 19 additions & 4 deletions src/services/emailQueueProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const { promisify } = require("util");
const redisClient = require("./redisServer");
const nodemailer = require("nodemailer");
const { json } = require("stream/consumers");
const cron = require("node-cron");

// Using promisify to convert the callback based to promise chains
const rpushAsync = promisify(redisClient.rPush).bind(redisClient);
Expand Down Expand Up @@ -79,13 +80,27 @@ async function processRetryQueue(retryQueueName, mainQueueName) {
}
}

// Periodic queue polling function
function pollQueues(mainQueueName, retryQueueName, dlqName) {
setInterval(() => processQueue(mainQueueName, retryQueueName, dlqName), 1000);
setInterval(() => processRetryQueue(retryQueueName, mainQueueName), 1000);
// Run cron jobs to poll the queue at specific time
// in this case we will poll the main queue at 12 am
// night and retry queue 2-3 hours later
function pollQueues(mainQueueName, retry_queue, dlqName) {
// Run the job at night(12 AM ) for main queue
cron.schedule("0 2 * * *", () => {
console.log(`Processing main queue at night...12 AM`);
processQueue(mainQueueName, retry_queue, dlqName);
});

// Run the job at night(2 AM ) for retry queue
cron.schedule("0 2 * * *", () => {
console.log(`Processing retry queue at night...2 AM`);
processRetryQueue(retry_queue, dlqName);
});
}

module.exports = {
pollEmailQueue: () => pollQueues("email_queue", "retry_queue", "email_dlq"),
pollInviteQueue: () =>
pollQueues("invite_queue", "retry_invite_queue", "invite_dlq"),
pollBarterNotification: () =>
pollQueues("barter_notification", "retry_queue", "email_dlq"),
};
15 changes: 15 additions & 0 deletions src/services/emailQueueProducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,22 @@ async function queueInviteEmailSending(mailOptions) {
}
}

async function queueBarterNotification(mailOptions) {
const job = json.stringify({
mailOptions,
retries: 0,
});
try {
await rpushAsync("barter_notification", job);
console.log(`Barter invite emails addded to queue`);
} catch (error) {
console.error(`Error adding emails to barter_notification queue`);
throw new Error(`Error adding emails to barter_notification queue`);
}
}

module.exports = {
queueEmailSending,
queueInviteEmailSending,
queueBarterNotification,
};

0 comments on commit 1c86135

Please sign in to comment.