Skip to content

Commit

Permalink
ft(socket):Add socket to handle realtime notification
Browse files Browse the repository at this point in the history
  • Loading branch information
leandreAlly committed May 29, 2024
1 parent d50fc2d commit d542e00
Show file tree
Hide file tree
Showing 10 changed files with 240 additions and 5 deletions.
121 changes: 121 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 @@ -52,6 +52,7 @@
"pg": "^8.9.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.29.0",
"socket.io": "^4.7.5",
"source-map": "^0.7.4",
"swagger-ui-express": "^4.6.1"
},
Expand Down
7 changes: 6 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-undef */
import express from "express";
import * as http from "http";
import session from "express-session";
import dotenv from "dotenv";
import cors from "cors";
Expand All @@ -12,12 +13,16 @@ import {
listenToUserProjectAssigned,
listenToLeadProjectAssigned,
} from "./system/utils/listenToEvent";
import { SocketUtil } from "./system/utils/SocketUtil";
import cronJob from "./system/utils/cronjob";

dotenv.config();

const PORT = process.env.PORT || 4000;

const app = express();
const server = http.createServer(app);
SocketUtil.config(server);
cronJob();
app.use(express.urlencoded({ extended: false }));
app.use(cors());
Expand Down Expand Up @@ -51,7 +56,7 @@ const initializeDatabase = async () => {
const start = () => {
try {
initializeDatabase();
app.listen({ port: PORT }, () =>
server.listen({ port: PORT }, () =>
process.stdout.write(`http://localhost:${PORT} \n`)
);
} catch (error) {
Expand Down
24 changes: 23 additions & 1 deletion src/documentation/notification/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import responses from "../responses";
const notification = {
"/notification": {
get: {
tags: ["Notification"],
tags: ["Notifications"],
security: [{ JWT: [] }],
summary: "get notifications",
parameters: [
Expand All @@ -29,6 +29,28 @@ const notification = {
responses,
},
},

"/notification/{notificationId}": {
patch: {
tags: ["Notifications"],
security: [{ JWT: [] }],
summary: "Update User notifications",
parameters: [
{
name: "notificationId",
in: "path",
description: "Id of the notification to be updated",
required: true,
schema: {
type: "string",
format: "uuid",
},
},
],
consumes: ["application/json"],
responses,
},
},
};

export default notification;
21 changes: 21 additions & 0 deletions src/restful/controllers/NotificationController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import NotificationService from "../../services/notificationService";
import { knownEvents, subscribe } from "../../system/utils/event.util";

// subscribe(knownEvents.)

export default class NotificationController {
static async getNotifications(req, res) {
Expand All @@ -19,4 +22,22 @@ export default class NotificationController {
});
}
}

static async markOneNotification(req, res) {
try {
await NotificationService.updateNotifications(
{ read: true },
{ id: req.params.notificationId, userId: req.user.id }
);

return res
.status(200)
.json({ message: "Marked one notification as read" });
} catch (err) {
return res.status(500).json({
error: err.message,
message: "Failed to update the notification",
});
}
}
}
16 changes: 16 additions & 0 deletions src/restful/middlewares/notificationMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
import NotificationService from "../../services/notificationService";

export const receivedPaginationFormat = async (req, res, next) => {
req.query = {
limit: req.query["limit"] || "10",
page: req.query["page"] || "1",
};
next();
};

export const checkIfHasNotificationId = async (req, res, next) => {
const notification = await NotificationService.getNotifications(
{
id: req.params.notificationId,
},
null,
null
);
if (notification.rows.length === 0) {
return res.status(404).json({ message: "Notification not found" });
}
next();
};
11 changes: 10 additions & 1 deletion src/restful/routes/notificationRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import NotificationController from "../controllers/NotificationController";

import protect from "../middlewares";
import { validatePagination } from "../../validations/notification.validation";
import { receivedPaginationFormat } from "../middlewares/notificationMiddleware";
import {
checkIfHasNotificationId,
receivedPaginationFormat,
} from "../middlewares/notificationMiddleware";

const notificationRouter = express.Router();

Expand All @@ -15,4 +18,10 @@ notificationRouter.get(
NotificationController.getNotifications
);

notificationRouter.patch(
"/:notificationId",
protect,
checkIfHasNotificationId,
NotificationController.markOneNotification
);
export default notificationRouter;
4 changes: 4 additions & 0 deletions src/services/notificationService.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ export default class NotificationService {
}
}

static async updateNotifications(field, query) {
return await Notification.update(field, { where: query });
}

static async getNotifications(query, limit, page) {
const offset = (page - 1) * limit;

Expand Down
23 changes: 23 additions & 0 deletions src/system/utils/SocketUtil.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Server } from "socket.io";

export class SocketUtil {
static io;
static socketEmit(key, data) {
SocketUtil.io.sockets.emit(key, data);
}

static config(server) {
SocketUtil.io = new Server(server, { cors: { origin: "*" } });

SocketUtil.io.on("connection", (socket) => {
console.log("Connected", socket.id);
socket.on("join_room", (data) => {
socket.join(data);
});
});
}
}

export const knownSockets = {
notification: "notification",
};
Loading

0 comments on commit d542e00

Please sign in to comment.