psi-notification-server
v1.0.0
Published
A custom module for real-time notifications built with Express, Socket.IO, and Sequelize. This module provides a methods to manage notifications with support for real-time updates via WebSockets.
Readme
PSI Notification Server
A custom module for real-time notifications built with Express, Socket.IO, and Sequelize. This module provides a methods to manage notifications with support for real-time updates via WebSockets.
Features
- Create, update, delete, and fetch notifications.
- Real-time notifications via WebSockets.
- Simple integration with an Express app.
- CORS management for different environments (production, development).
- Sequelize-based ORM for easy interaction with the database.
Prerequisites
- Node.js >= 14.x
- PostgreSQL or any other supported database for Sequelize
- Express.js
- Socket.IO
Installation
To integrate this module into your Express app:
Install the module:
Using npm:
npm install psi-notification-serverOr using yarn
yarn add psi-notification-serverSet up environment variables: Add the following environment variables to your
.envfile (or in the server environment):DB_CONNECTION_STRING=postgres://username:password@localhost:5432/<dbname> NODE_ENV=development # or 'production'
Available Methods:
import { initNotificationModule } from 'psi-notification-server';
const { initializeSocket, addNotification, getNotificationList, updateNotificationStatus, deleteNotification } =
await initNotificationModule('database-connection-string');Initialize Socket Connection:
const app = express();
const server = http.createServer(app);
initializeSocket(server);Notification Props (Interface):
interface NotificationProps {
receiver_id: number;
sender_id: number;
title: string;
message: string;
image_url?: string;
redirect_route?: string;
type?: string;
status?: string;
created_at?: Date;
updated_at?: Date;
}Create Notification:
Method: addNotification()
Required Params
notificationData: NotificationProps,
userId?: stringExample
const result = await addNotification(notificationData, userId);Read Notification:
Method: getNotificationList()
Required Params
receiverId: string,
page: number = 1,
pageSize: number = 10,
status?: string[] // ['new', 'unread', 'read']Example
const { data, error } = await getNotificationList('receiverId', 1, 15, ['new', 'unread', 'read']);Update Notification:
Method: updateNotificationStatus()
Required Params
receiverId: string;
status: string;
notificationIds?: string[]; // OptionalExample
const result = await updateNotificationStatus({
receiverId,
'read',
['notificationId_1', 'notificationId_2', ...],
});Delete Notification:
Method: deleteNotification()
Required Params
notificationId: string;Example
const result = await deleteNotification(notificationId);Usage
Example: Using the Notification Module in Express
Here’s an example of how to set up and use the notification module in an Express app:
import express, { Request, Response } from 'express';
import http from 'http';
import { initNotificationModule } from 'psi-notification-server';
import cors from 'cors';
import dotenv from 'dotenv';
dotenv.config();
// Setup the database connection string
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error('DATABASE_URL is not defined in .env');
}
const app = express();
const server = http.createServer(app);
// Middleware and CORS setup
app.use(express.json());
app.use(cors({ origin: '*', methods: ['GET', 'POST', 'PUT'], credentials: true }));
// Initialize Notification Module
async function initializeNotificationModuleAndRoutes() {
try {
const { initializeSocket, getNotificationList, updateNotificationStatus, addNotification, deleteNotification } = await initNotificationModule(connectionString);
// Initialize Socket.IO
initializeSocket(server);
// Define the notification routes
app.get('/notifications/list/:receiverId', async (req: Request, res: Response) => {
const { receiverId } = req.params;
const { page = '1', pageSize = '10', status } = req.query;
const statusArray = status ? String(status).split(',') : ['new'];
const { data, error } = await getNotificationList(receiverId, Number(page), Number(pageSize), statusArray);
if (error) return res.status(500).json({ message: error });
return res.status(200).json({ data });
});
// Insert a new notification
app.post('/notifications/insert', async (req: Request, res: Response) => {
const { notification, userId } = req.body;
const requiredFields: (keyof INotification)[] = ['receiver_id', 'sender_id', 'title', 'message', 'status'];
const missingFields = requiredFields.filter((field) => !notification[field]);
if (missingFields.length > 0) {
return res.status(400).json({ error: `Missing required fields: ${missingFields.join(', ')}` });
}
const result = await addNotification(notification, userId); // userId is optional
return res.json({ data: result.data, error: result.error });
});
// Start the server
server.listen(process.env.PORT, () => {
console.log('Server is running on port 3001');
});
} catch (error) {
console.error('Error initializing notification module:', error);
}
}
// Call the initialization function
initializeNotificationModuleAndRoutes();