atozas-push-notification
Version:
Real-time push notifications across platforms using socket.io
485 lines (379 loc) ⢠11.8 kB
Markdown
# Atozas Push Notification
š Real-time push notifications across platforms using Socket.IO
[](https://badge.fury.io/js/atozas-push-notification)
[](https://opensource.org/licenses/MIT)
## Features
ā
**Cross-Platform Support**: Web ā Web, Web ā Mobile, Mobile ā Web, Mobile ā Mobile
ā
**Real-time Communication**: Powered by Socket.IO
ā
**User Management**: Auto-manage connected users with socket IDs
ā
**Group Messaging**: Support for group notifications
ā
**Direct Messaging**: Send notifications to specific users
ā
**Broadcast**: Send notifications to all connected users
ā
**Auto-Reconnection**: Automatic reconnection on disconnect
ā
**TypeScript Support**: Full TypeScript definitions included
ā
**Easy Integration**: Simple API for quick implementation
## Installation
```bash
npm install atozas-push-notification
```
## Quick Start
### Server Setup
```javascript
const { AtozasPushNotificationServer } = require('atozas-push-notification');
// Create server instance
const notificationServer = new AtozasPushNotificationServer({
port: 3000,
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
// Send notification to a specific user
notificationServer.sendNotification({
to: 'user',
target: 'user123',
notification: {
id: 'notif_1',
title: 'Welcome!',
message: 'Thank you for joining our platform',
timestamp: Date.now(),
priority: 'high'
}
});
```
### Client Setup
```javascript
const { AtozasPushNotificationClient } = require('atozas-push-notification');
// Create client instance
const notificationClient = new AtozasPushNotificationClient({
url: 'http://localhost:3000',
autoConnect: true,
reconnection: true
});
// Authenticate user
notificationClient.authenticate({
userId: 'user123',
deviceId: 'device456',
platform: 'web'
});
// Listen for notifications
notificationClient.onNotification((notification, options) => {
console.log('Received notification:', notification);
// Acknowledge notification
notificationClient.acknowledgeNotification(notification.id);
});
// Listen for connection status
notificationClient.onConnection((connected) => {
console.log('Connection status:', connected ? 'Connected' : 'Disconnected');
});
```
## API Documentation
### Server API
#### Constructor
```javascript
const server = new AtozasPushNotificationServer(config);
```
**Config Options:**
```typescript
interface ServerConfig {
port?: number; // Server port (optional if using custom HTTP server)
cors?: any; // CORS configuration
allowEIO3?: boolean; // Allow Engine.IO v3 clients
transports?: string[]; // Available transports ['websocket', 'polling']
}
```
#### Methods
##### `sendNotification(params)`
Send notifications to users, groups, or broadcast to all.
```javascript
server.sendNotification({
to: 'user', // 'user' | 'group' | 'broadcast'
target: 'user123', // userId for 'user', groupId for 'group', undefined for 'broadcast'
notification: {
id: 'unique_id',
title: 'Notification Title',
message: 'Notification message',
timestamp: Date.now(),
priority: 'high', // 'low' | 'normal' | 'high'
data: { custom: 'data' }
},
options: {
persist: true,
sound: true,
vibrate: true
}
});
```
##### `sendToUsers(userIds, notification, options?)`
Send notification to multiple users.
```javascript
server.sendToUsers(
['user1', 'user2', 'user3'],
{
id: 'bulk_notif_1',
title: 'Bulk Notification',
message: 'This is sent to multiple users',
timestamp: Date.now()
}
);
```
##### `addUserToGroup(userId, groupId)`
Add user to a group programmatically.
```javascript
server.addUserToGroup('user123', 'group_vip');
```
##### `removeUserFromGroup(userId, groupId)`
Remove user from a group.
```javascript
server.removeUserFromGroup('user123', 'group_vip');
```
##### `getConnectedUsers()`
Get list of all connected users.
```javascript
const users = server.getConnectedUsers();
console.log('Connected users:', users);
```
##### `isUserOnline(userId)`
Check if a specific user is online.
```javascript
const isOnline = server.isUserOnline('user123');
```
##### `getStats()`
Get server statistics.
```javascript
const stats = server.getStats();
// Returns: { connectedUsers: number, totalGroups: number, groupStats: [...] }
```
### Client API
#### Constructor
```javascript
const client = new AtozasPushNotificationClient(config);
```
**Config Options:**
```typescript
interface ClientConfig {
url: string; // Server URL
autoConnect?: boolean; // Auto-connect on instantiation (default: true)
reconnection?: boolean; // Enable auto-reconnection (default: true)
reconnectionAttempts?: number; // Max reconnection attempts (default: 5)
reconnectionDelay?: number; // Initial reconnection delay (default: 1000ms)
reconnectionDelayMax?: number; // Max reconnection delay (default: 5000ms)
timeout?: number; // Connection timeout (default: 20000ms)
forceNew?: boolean; // Force new connection (default: false)
}
```
#### Methods
##### `authenticate(userInfo)`
Authenticate user with the server.
```javascript
client.authenticate({
userId: 'user123',
deviceId: 'device456', // Optional
platform: 'web', // 'web' | 'mobile' | 'desktop'
metadata: { version: '1.0' } // Optional custom data
});
```
##### `joinGroup(groupId)`
Join a group for group notifications.
```javascript
client.joinGroup('group_announcements');
```
##### `leaveGroup(groupId)`
Leave a group.
```javascript
client.leaveGroup('group_announcements');
```
##### Event Handlers
```javascript
// Listen for notifications
client.onNotification((notification, options) => {
console.log('New notification:', notification);
});
// Listen for connection status changes
client.onConnection((connected) => {
console.log('Connection:', connected ? 'Connected' : 'Disconnected');
});
// Listen for errors
client.onError((error) => {
console.error('Error:', error);
});
// Listen for user status updates
client.onUserStatus((userId, online) => {
console.log(`User ${userId} is ${online ? 'online' : 'offline'}`);
});
```
##### Utility Methods
```javascript
// Get connection status
const isConnected = client.getConnectionStatus();
// Get current user info
const userInfo = client.getUserInfo();
// Manually connect/disconnect
await client.connect();
client.disconnect();
// Acknowledge notification
client.acknowledgeNotification('notification_id');
// Request user status
client.requestUserStatus('user123');
```
## Advanced Usage
### Custom Notification Types
```javascript
const { createNotification } = require('atozas-push-notification');
// Create notification with helper function
const notification = createNotification(
'Order Update',
'Your order #12345 has been shipped!',
{ orderId: '12345', trackingNumber: 'TN123456' },
{ priority: 'high', category: 'order' }
);
server.sendNotification({
to: 'user',
target: 'customer123',
notification
});
```
### Group Management
```javascript
// Server-side group management
server.addUserToGroup('user1', 'premium_users');
server.addUserToGroup('user2', 'premium_users');
// Send to group
server.sendNotification({
to: 'group',
target: 'premium_users',
notification: {
id: 'premium_offer',
title: 'Exclusive Offer',
message: 'Special discount for premium users!',
timestamp: Date.now()
}
});
// Client-side group joining
client.joinGroup('premium_users');
```
### Broadcast Notifications
```javascript
// Send to all connected users
server.sendNotification({
to: 'broadcast',
notification: {
id: 'maintenance_alert',
title: 'Maintenance Notice',
message: 'System maintenance will begin in 30 minutes',
timestamp: Date.now(),
priority: 'high'
}
});
```
### Error Handling
```javascript
// Client error handling
client.onError((error) => {
console.error('Notification client error:', error);
// Implement custom error handling
if (error.message.includes('connection')) {
// Handle connection errors
setTimeout(() => client.connect(), 5000);
}
});
// Server error handling
server.on('error', (error) => {
console.error('Notification server error:', error);
});
```
## TypeScript Support
The package includes full TypeScript definitions:
```typescript
import {
AtozasPushNotificationClient,
AtozasPushNotificationServer,
NotificationData,
UserInfo,
ClientConfig,
ServerConfig
} from 'atozas-push-notification';
const client: AtozasPushNotificationClient = new AtozasPushNotificationClient({
url: 'http://localhost:3000',
reconnection: true
});
const userInfo: UserInfo = {
userId: 'user123',
platform: 'web',
deviceId: 'device456'
};
client.authenticate(userInfo);
```
## Integration Examples
### Express.js Integration
```javascript
const express = require('express');
const { AtozasPushNotificationServer } = require('atozas-push-notification');
const app = express();
const server = require('http').createServer(app);
// Create notification server with existing HTTP server
const notificationServer = new AtozasPushNotificationServer();
notificationServer.io.attach(server);
app.post('/send-notification', (req, res) => {
const { userId, title, message } = req.body;
const success = notificationServer.sendNotification({
to: 'user',
target: userId,
notification: {
id: Date.now().toString(),
title,
message,
timestamp: Date.now()
}
});
res.json({ success });
});
server.listen(3000);
```
### React Integration
```jsx
import React, { useEffect, useState } from 'react';
import { AtozasPushNotificationClient } from 'atozas-push-notification';
const NotificationComponent = () => {
const [client, setClient] = useState(null);
const [notifications, setNotifications] = useState([]);
const [connected, setConnected] = useState(false);
useEffect(() => {
const notificationClient = new AtozasPushNotificationClient({
url: 'http://localhost:3000'
});
notificationClient.authenticate({
userId: 'user123',
platform: 'web'
});
notificationClient.onConnection(setConnected);
notificationClient.onNotification((notification) => {
setNotifications(prev => [...prev, notification]);
notificationClient.acknowledgeNotification(notification.id);
});
setClient(notificationClient);
return () => {
notificationClient.disconnect();
};
}, []);
return (
<div>
<div>Status: {connected ? 'Connected' : 'Disconnected'}</div>
<div>
{notifications.map(notif => (
<div key={notif.id} className="notification">
<h4>{notif.title}</h4>
<p>{notif.message}</p>
</div>
))}
</div>
</div>
);
};
```
## License
MIT Ā© Atozas
## Support
For issues and questions, please visit our [GitHub repository](https://github.com/atozas/atozas-push-notification).
---
**Happy coding with real-time notifications! š**