empowerx-alert-client
v1.0.7
Published
EmpowerX Alert System - Client SDK for notifications
Maintainers
Readme
EmpowerX Alert Client SDK
A TypeScript/JavaScript client SDK for the EmpowerX Alert Notification System.
Installation
npm install empowerx-alert-client
# or
pnpm add empowerx-alert-clientCLI - Auto Generate Files
After installing, use the CLI to auto-generate all files:
# Generate everything (config, bell, hook, provider, vue)
empowerx-alert all
# Generate specific files
empowerx-alert init # Client configuration
empowerx-alert bell # Notification bell component
empowerx-alert hook # React useNotifications hook
empowerx-alert provider # React context provider
empowerx-alert vue # Vue 3 composable
# Custom output directory
empowerx-alert all --output ./src/notifications
# Custom API URL
empowerx-alert init --api-url https://api.example.comFeatures
- REST API client for notification management
- WebSocket client for real-time notifications
- Full TypeScript support
- Works with React, Vue, Angular, Next.js, and plain JavaScript
- CLI for auto-generating components and configurations
Quick Start
REST API Client
import { createEmpowerxAlertClient } from 'empowerx-alert-client';
const client = createEmpowerxAlertClient({
baseUrl: 'http://localhost:3000',
token: 'your-jwt-token',
});WebSocket for Real-time Notifications
import { createEmpowerxAlertWebSocket } from 'empowerx-alert-client';
const ws = createEmpowerxAlertWebSocket({
baseUrl: 'http://localhost:3000',
token: 'your-jwt-token',
});
ws.connect();
ws.onNotification((notification) => {
console.log('New notification:', notification);
// Show toast/alert to user
});API Reference
createEmpowerxAlertClient(options)
Creates a REST API client instance.
Options:
baseUrl(string): Base URL of the EmpowerX Alert APItoken(string, optional): JWT authentication tokenapiKey(string, optional): API key for authentication
Client Methods
getNotificationTypes()
Get all available notification types.
const types = await client.getNotificationTypes();createNotification(dto)
Create and send a notification.
await client.createNotification({
typeCode: 'task.assigned',
recipientIds: ['user-123'],
tenantId: 'tenant-456',
variables: {
taskName: 'Review Q1 Report',
assignerName: 'John Doe',
taskPriority: 'High',
dueDate: '2026-02-28',
taskId: 'task-001',
},
priority: 'high',
channels: ['in_app', 'email'],
});getNotifications(params)
Get paginated notifications.
const result = await client.getNotifications({
page: 1,
limit: 20,
unreadOnly: false,
});markAsRead(id)
Mark a notification as read.
await client.markAsRead('notification-id');markAllAsRead()
Mark all notifications as read.
await client.markAllAsRead();deleteNotification(id)
Delete a notification.
await client.deleteNotification('notification-id');getUnreadCount()
Get count of unread notifications.
const { count } = await client.getUnreadCount();getUserPreferences()
Get user notification preferences.
const prefs = await client.getUserPreferences();updateUserPreferences(dto)
Update user notification preferences.
await client.updateUserPreferences({
channels: {
inApp: true,
email: true,
sms: false,
push: true,
webhook: false,
},
quietHoursEnabled: true,
quietHoursStart: '22:00',
quietHoursEnd: '08:00',
});WebSocket Client Methods
connect()
Connect to WebSocket server.
disconnect()
Disconnect from WebSocket server.
onNotification(handler)
Listen for incoming notifications.
ws.onNotification((notification) => {
// Handle notification
});offNotification(handler)
Remove notification listener.
subscribeToNotificationType(typeCode)
Subscribe to specific notification type.
ws.subscribeToNotificationType('task.assigned');isConnected()
Check WebSocket connection status.
React Implementation Example
import { createEmpowerxAlertClient, createEmpowerxAlertWebSocket, Notification } from 'empowerx-alert-client';
import { useState, useEffect, useCallback } from 'react';
const useNotifications = (baseUrl: string, token: string, userId: string) => {
const [notifications, setNotifications] = useState<Notification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const [isConnected, setIsConnected] = useState(false);
const client = createEmpowerxAlertClient({ baseUrl, token });
const ws = createEmpowerxAlertWebSocket({ baseUrl, token, userId });
const fetchNotifications = useCallback(async () => {
const result = await client.getNotifications({ page: 1, limit: 20 });
setNotifications(result.data);
setUnreadCount(result.data.filter(n => !n.readAt).length);
}, [client]);
const markAsRead = async (id: string) => {
await client.markAsRead(id);
setNotifications(prev =>
prev.map(n => n.id === id ? { ...n, readAt: new Date().toISOString() } : n)
);
setUnreadCount(prev => Math.max(0, prev - 1));
};
const markAllAsRead = async () => {
await client.markAllAsRead();
setNotifications(prev => prev.map(n => ({ ...n, readAt: new Date().toISOString() })));
setUnreadCount(0);
};
useEffect(() => {
fetchNotifications();
ws.connect();
setIsConnected(true);
ws.onNotification((notification) => {
setNotifications(prev => [notification, ...prev]);
setUnreadCount(prev => prev + 1);
// Optional: Show toast notification
});
return () => {
ws.disconnect();
};
}, [ws, fetchNotifications]);
return {
notifications,
unreadCount,
isConnected,
markAsRead,
markAllAsRead,
refresh: fetchNotifications,
};
};
export default useNotifications;Vue 3 Implementation Example
import { createEmpowerxAlertClient, createEmpowerxAlertWebSocket, Notification } from 'empowerx-alert-client';
import { ref, onMounted, onUnmounted } from 'vue';
export function useNotifications(baseUrl: string, token: string, userId: string) {
const notifications = ref<Notification[]>([]);
const unreadCount = ref(0);
const isConnected = ref(false);
const client = createEmpowerxAlertClient({ baseUrl, token });
const ws = createEmpowerxAlertWebSocket({ baseUrl, token, userId });
const fetchNotifications = async () => {
const result = await client.getNotifications({ page: 1, limit: 20 });
notifications.value = result.data;
unreadCount.value = result.data.filter(n => !n.readAt).length;
};
const markAsRead = async (id: string) => {
await client.markAsRead(id);
const notif = notifications.value.find(n => n.id === id);
if (notif && !notif.readAt) {
notif.readAt = new Date().toISOString();
unreadCount.value--;
}
};
onMounted(() => {
fetchNotifications();
ws.connect();
isConnected.value = true;
ws.onNotification((notification) => {
notifications.value.unshift(notification);
unreadCount.value++;
});
});
onUnmounted(() => {
ws.disconnect();
});
return {
notifications,
unreadCount,
isConnected,
markAsRead,
refresh: fetchNotifications,
};
}Next.js Implementation Example
'use client';
import { createEmpowerxAlertClient, createEmpowerxAlertWebSocket, Notification } from 'empowerx-alert-client';
import { useEffect, useState, useCallback } from 'react';
export function useNotificationCenter(baseUrl: string, token: string, userId: string, tenantId: string) {
const [notifications, setNotifications] = useState<Notification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const client = createEmpowerxAlertClient({ baseUrl, token });
const ws = createEmpowerxAlertWebSocket({ baseUrl, token, userId, tenantId });
const fetchNotifications = useCallback(async () => {
setIsLoading(true);
try {
const result = await client.getNotifications({ page: 1, limit: 50 });
setNotifications(result.data);
setUnreadCount(result.data.filter(n => !n.readAt).length);
} finally {
setIsLoading(false);
}
}, [client]);
const sendNotification = async (typeCode: string, variables: Record<string, string>, recipientIds: string[]) => {
return client.createNotification({
typeCode,
tenantId,
recipientIds,
variables,
});
};
useEffect(() => {
fetchNotifications();
ws.connect();
ws.onNotification((notification) => {
setNotifications(prev => [notification, ...prev]);
setUnreadCount(prev => prev + 1);
});
return () => {
ws.disconnect();
};
}, [ws, fetchNotifications]);
return {
notifications,
unreadCount,
isLoading,
sendNotification,
markAsRead: (id: string) => client.markAsRead(id).then(fetchNotifications),
markAllAsRead: () => client.markAllAsRead().then(fetchNotifications),
refresh: fetchNotifications,
};
}Vanilla JavaScript Example
<script type="module">
import { createEmpowerxAlertClient, createEmpowerxAlertWebSocket } from 'empowerx-alert-client';
const client = createEmpowerxAlertClient({
baseUrl: 'http://localhost:3000',
token: 'your-token',
});
const ws = createEmpowerxAlertWebSocket({
baseUrl: 'http://localhost:3000',
token: 'your-token',
});
// Fetch notifications
const { data: notifications } = await client.getNotifications();
console.log(notifications);
// Listen for real-time notifications
ws.connect();
ws.onNotification((notification) => {
showToast(notification.title, notification.body);
});
function showToast(title, body) {
// Your toast implementation
alert(`${title}: ${body}`);
}
</script>Notification Types Reference
| Category | Type Code | Description |
|----------|-----------|-------------|
| Approval | approval.requested | New approval request |
| | approval.approved | Item approved |
| | approval.rejected | Item rejected |
| Task | task.assigned | New task assigned |
| | task.completed | Task completed |
| | task.overdue | Task overdue |
| | task.reminder | Task reminder |
| System | system.alert | System alert |
| | system.maintenance | Maintenance notice |
| Workflow | workflow.completed | Workflow finished |
| | workflow.failed | Workflow failed |
| Message | message.received | New message |
| | message.mention | Mentioned in chat |
| Meeting | meeting.invitation | Meeting invite |
| | meeting.reminder | Meeting reminder |
| Payment | payment.received | Payment received |
| | payment.failed | Payment failed |
| Document | document.shared | Document shared |
| Report | report.generated | Report ready |
Error Handling
try {
await client.createNotification({ ... });
} catch (error) {
if (error.message.includes('401')) {
// Handle unauthorized - refresh token
} else if (error.message.includes('403')) {
// Handle forbidden - insufficient permissions
} else {
// Handle other errors
}
}TypeScript Types
import type {
Notification,
NotificationType,
UserPreferences,
CreateNotificationDto,
NotificationChannel,
PaginatedResponse,
} from 'empowerx-alert-client';License
MIT
