ironnotify-js/README.md

368 lines
9.3 KiB
Markdown

<p align="center">
<a href="https://ironnotify.com">
<img src="https://ironnotify.com/logo.png" alt="IronNotify" width="120" />
</a>
</p>
<h1 align="center">IronNotify SDK for JavaScript/TypeScript</h1>
<p align="center">
<strong>Event notifications and alerts for modern applications</strong>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/@ironservices/notify"><img src="https://img.shields.io/npm/v/@ironservices/notify.svg" alt="npm version"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
</p>
<p align="center">
<a href="https://ironnotify.com">Website</a>
<a href="https://ironnotify.com/docs">Documentation</a>
<a href="https://ironnotify.com/docs/js">JavaScript Guide</a>
<a href="https://git.marketally.com/ironservices">Git</a>
</p>
---
**IronNotify** helps you send event notifications and alerts to your users instantly. Built for developers who want simple, powerful notification infrastructure without the complexity.
## 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)
## Documentation
For complete documentation, visit [ironnotify.com/docs](https://ironnotify.com/docs).
## Other SDKs
| Platform | Package |
|----------|---------|
| .NET | [IronNotify.Client](https://git.marketally.com/ironservices/ironnotify-dotnet) |
| Python | [ironnotify](https://git.marketally.com/ironservices/ironnotify-python) |
| Go | [ironnotify-go](https://git.marketally.com/ironservices/ironnotify-go) |
| Java | [ironnotify-java](https://git.marketally.com/ironservices/ironnotify-java) |
| Rust | [ironnotify](https://git.marketally.com/ironservices/ironnotify-rust) |
## Support
- **Documentation**: [ironnotify.com/docs](https://ironnotify.com/docs)
- **Email**: dev@ironservices.io
- **Issues**: [git.marketally.com/ironservices/ironnotify-js/issues](https://git.marketally.com/ironservices/ironnotify-js/issues)
## License
MIT License - see [LICENSE](LICENSE) for details.