ironnotify-js/README.md

332 lines
7.9 KiB
Markdown

# IronNotify SDK for JavaScript/TypeScript
Event notifications and alerts SDK for JavaScript/TypeScript applications. Send notifications, receive real-time updates, and manage notification state.
[![npm version](https://img.shields.io/npm/v/@ironservices/notify.svg)](https://www.npmjs.com/package/@ironservices/notify)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
## Installation
```bash
npm install @ironservices/notify
```
## Quick Start
### Send a Simple Notification
```typescript
import { NotifyClient } from '@ironservices/notify';
const client = new NotifyClient({
apiKey: 'ak_live_xxxxx',
});
// Send a simple notification
await client.notify('order.created', 'New Order Received', {
message: 'Order #1234 has been placed',
severity: 'success',
metadata: { orderId: '1234', amount: 99.99 },
});
```
### Fluent Event Builder
```typescript
import { NotifyClient } from '@ironservices/notify';
const client = new NotifyClient({ apiKey: 'ak_live_xxxxx' });
// Build complex notifications with the fluent API
await client.event('payment.failed')
.withTitle('Payment Failed')
.withMessage('The payment for order #1234 could not be processed')
.withSeverity('error')
.withMetadata({ orderId: '1234', reason: 'Card declined' })
.withAction({ label: 'Retry Payment', url: '/orders/1234/retry', style: 'primary' })
.withAction({ label: 'Contact Support', action: 'open_support' })
.forUser('user-123')
.withDeduplicationKey('payment-failed-1234')
.expiresIn(24 * 60 * 60 * 1000) // 24 hours
.send();
```
### Real-Time Notifications
```typescript
import { NotifyClient } from '@ironservices/notify';
const client = new NotifyClient({ apiKey: 'ak_live_xxxxx' });
// Set up handlers
client.onNotification((notification) => {
console.log('New notification:', notification.title);
showToast(notification);
});
client.onUnreadCountChange((count) => {
updateBadge(count);
});
client.onConnectionStateChange((state) => {
console.log('Connection state:', state);
});
// Connect and subscribe
client.connect();
client.subscribeToUser('user-123');
client.subscribeToApp(); // App-wide notifications
```
### Global Client (Convenience API)
```typescript
import * as ironnotify from '@ironservices/notify';
// Initialize once
ironnotify.init({ apiKey: 'ak_live_xxxxx' });
// Use anywhere
await ironnotify.notify('user.signup', 'New User Registered');
// Connect to real-time
ironnotify.connect();
ironnotify.subscribeToUser('user-123');
ironnotify.onNotification((n) => console.log(n));
// Clean up
ironnotify.close();
```
## Configuration
```typescript
import { NotifyClient } from '@ironservices/notify';
const client = new NotifyClient({
apiKey: 'ak_live_xxxxx',
apiBaseUrl: 'https://api.ironnotify.com',
wsUrl: 'wss://ws.ironnotify.com',
debug: false,
enableOfflineQueue: true,
maxOfflineQueueSize: 100,
autoReconnect: true,
maxReconnectAttempts: 5,
reconnectDelay: 1000,
});
```
### Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | string | required | Your API key (ak_live_xxx or ak_test_xxx) |
| `apiBaseUrl` | string | 'https://api.ironnotify.com' | API base URL |
| `wsUrl` | string | 'wss://ws.ironnotify.com' | WebSocket URL |
| `debug` | boolean | false | Enable debug logging |
| `enableOfflineQueue` | boolean | true | Queue notifications when offline |
| `maxOfflineQueueSize` | number | 100 | Max offline queue size |
| `autoReconnect` | boolean | true | Auto-reconnect WebSocket |
| `maxReconnectAttempts` | number | 5 | Max reconnection attempts |
| `reconnectDelay` | number | 1000 | Base reconnection delay (ms) |
## Features
- **Simple Notifications**: Send notifications with one line of code
- **Fluent Builder**: Build complex notifications with an intuitive API
- **Real-Time Updates**: Receive notifications instantly via WebSocket
- **Offline Queue**: Notifications are queued when offline and sent when back online
- **Auto-Reconnect**: Automatic WebSocket reconnection with exponential backoff
- **Type Safety**: Full TypeScript support with comprehensive type definitions
- **Universal**: Works in Node.js and browsers
## Notification Options
### Severity Levels
```typescript
type SeverityLevel = 'info' | 'success' | 'warning' | 'error' | 'critical';
await client.notify('alert', 'System Alert', { severity: 'critical' });
```
### Actions
```typescript
await client.event('order.shipped')
.withTitle('Order Shipped')
.withAction({
label: 'Track Package',
url: 'https://tracking.example.com/123',
style: 'primary',
})
.withAction({
label: 'View Order',
action: 'view_order', // Custom action identifier
style: 'default',
})
.send();
```
### Deduplication
Prevent duplicate notifications:
```typescript
await client.event('reminder')
.withTitle('Daily Reminder')
.withDeduplicationKey('daily-reminder-2024-01-15')
.send();
```
### Grouping
Group related notifications:
```typescript
await client.event('comment.new')
.withTitle('New Comment')
.withGroupKey('post-123-comments')
.send();
```
### Expiration
Set notification expiration:
```typescript
// Expires in 1 hour
await client.event('flash_sale')
.withTitle('Flash Sale!')
.expiresIn(60 * 60 * 1000)
.send();
// Expires at specific time
await client.event('event_reminder')
.withTitle('Event Tomorrow')
.expiresOn(new Date('2024-01-16T09:00:00Z'))
.send();
```
## Managing Notifications
### Get Notifications
```typescript
// Get all notifications
const notifications = await client.getNotifications();
// With options
const unread = await client.getNotifications({
limit: 10,
offset: 0,
unreadOnly: true,
});
```
### Mark as Read
```typescript
// Mark single notification
await client.markAsRead('notification-id');
// Mark all as read
await client.markAllAsRead();
```
### Get Unread Count
```typescript
const count = await client.getUnreadCount();
console.log(`You have ${count} unread notifications`);
```
## WebSocket Connection States
```typescript
type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
client.onConnectionStateChange((state) => {
switch (state) {
case 'connected':
console.log('Connected to real-time notifications');
break;
case 'reconnecting':
console.log('Reconnecting...');
break;
case 'disconnected':
console.log('Disconnected');
break;
}
});
// Check current state
console.log(client.connectionState);
```
## Offline Support
Notifications are automatically queued when offline:
```typescript
const client = new NotifyClient({
apiKey: 'ak_live_xxxxx',
enableOfflineQueue: true,
maxOfflineQueueSize: 100,
});
// This will be queued if offline
await client.notify('event', 'Title');
// Manually flush the queue
await client.flush();
```
## React Example
```tsx
import { useEffect, useState } from 'react';
import { NotifyClient, Notification } from '@ironservices/notify';
function useNotifications(apiKey: string, userId: string) {
const [notifications, setNotifications] = useState<Notification[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
useEffect(() => {
const client = new NotifyClient({ apiKey });
client.onNotification((notification) => {
setNotifications(prev => [notification, ...prev]);
});
client.onUnreadCountChange(setUnreadCount);
client.connect();
client.subscribeToUser(userId);
// Load initial notifications
client.getNotifications().then(setNotifications);
client.getUnreadCount().then(setUnreadCount);
return () => client.close();
}, [apiKey, userId]);
return { notifications, unreadCount };
}
```
## Requirements
- Node.js 16+ or modern browser
- Fetch API (native in modern environments)
- WebSocket API (for real-time features)
## Links
- [Documentation](https://www.ironnotify.com/docs)
- [Dashboard](https://www.ironnotify.com)
## License
MIT License - see [LICENSE](LICENSE) for details.