@roarpush/node-sdk
v1.1.1
Published
Official Node.js SDK for RoarPush — multi-channel notification and audience management platform
Maintainers
Readme
@roarpush/node-sdk
Production-grade Node.js SDK for the RoarPush Notification Platform.
Designed for large-scale deployments supporting 15M+ users and 50k+ tenants.
Features
- 🚀 Full API Coverage - All RoarPush APIs with TypeScript types
- 🔄 Automatic Retries - Exponential backoff with jitter
- 🛡️ Rate Limit Handling - Smart rate limit awareness and callbacks
- 📊 Pagination Helpers - Async iterators for large datasets
- 🔐 Multiple Auth Methods - API key and JWT token support
- 📝 Full TypeScript Support - Complete type definitions
- ⚡ Production Ready - Built for high-volume applications
Installation
npm install @roarpush/node-sdk
# or
yarn add @roarpush/node-sdk
# or
pnpm add @roarpush/node-sdkQuick Start
import { RoarPush } from '@roarpush/node-sdk';
// Initialize with API key
const roarpush = new RoarPush({
apiKey: 'your-api-key',
baseURL: 'https://core-prod.roarpush.io/v1', // optional, this is the default
});
// Send a notification
const job = await roarpush.notifications.send({
target_type: 'segment',
segment_id: 123,
title: 'Hello!',
body: 'Welcome to our app',
channels: ['push', 'in_app'],
});
console.log(`Notification job created: ${job.id}`);Configuration
const roarpush = new RoarPush({
// Required: API key or access token
apiKey: 'your-api-key',
// OR for admin operations
accessToken: 'your-jwt-token',
// Optional settings
baseURL: 'https://core-prod.roarpush.io/v1',
timeout: 30000, // Request timeout (default: 30s)
maxRetries: 3, // Max retry attempts (default: 3)
retryDelay: 1000, // Initial retry delay (default: 1s)
debug: false, // Enable debug logging
// Callbacks
onRateLimit: (info) => {
console.log(`Rate limit: ${info.remaining}/${info.limit}`);
},
onError: (error) => {
console.error(`API error: ${error.message}`);
},
});Resources
Audiences
// Create or update audience
const audience = await roarpush.audiences.upsert({
external_user_id: 'user-123',
email: '[email protected]',
first_name: 'John',
custom_attributes: { plan: 'premium' },
});
// Get by external ID
const user = await roarpush.audiences.getByExternalId('user-123');
// Search audiences
const { data, pagination } = await roarpush.audiences.list({
tags: ['premium'],
country: 'US',
limit: 50,
});
// Iterate all audiences
for await (const audience of roarpush.audiences.listAll()) {
console.log(audience.external_user_id);
}Devices
// Register device
const device = await roarpush.devices.register({
external_user_id: 'user-123',
device_token: 'fcm-token-here',
platform: 'android',
app_version: '1.0.0',
});
// Update FCM token
await roarpush.devices.updateToken({
old_token: 'old-fcm-token',
device_token: 'new-fcm-token',
});
// Deactivate on logout
await roarpush.devices.deactivate({
external_user_id: 'user-123',
});Notifications
// Send to single user
const job = await roarpush.notifications.sendToUser('user-123', {
title: 'Order Confirmed',
body: 'Your order #12345 has been confirmed',
data: { order_id: '12345' },
channels: ['push', 'in_app'],
});
// Send to segment
await roarpush.notifications.sendToSegment(123, {
template_id: 456,
scheduled_at: '2024-01-15T10:00:00Z',
});
// Broadcast to all users
await roarpush.notifications.broadcast({
title: 'App Update Available',
body: 'Check out our new features!',
});
// Wait for completion
const completed = await roarpush.notifications.waitForCompletion(job.id);In-App Notifications
// Get badge count
const badge = await roarpush.inAppNotifications.getBadge('user-123');
console.log(`Unread: ${badge.unread}`);
// List notifications
const { data } = await roarpush.inAppNotifications.list('user-123', {
is_read: false,
limit: 20,
});
// Mark as read
await roarpush.inAppNotifications.markAsRead('notification-id');
// Mark multiple as read
await roarpush.inAppNotifications.markMultipleAsRead({
notification_ids: ['id-1', 'id-2', 'id-3'],
});Segments
// Create dynamic segment
const segment = await roarpush.segments.create({
name: 'Premium US Users',
is_dynamic: true,
filter_criteria: {
operator: 'and',
conditions: [
{ field: 'country', operator: 'eq', value: 'US' },
{ field: 'custom_attributes.plan', operator: 'eq', value: 'premium' },
],
},
});
// Refresh segment
await roarpush.segments.refresh(segment.id);
// Get member count
const { member_count } = await roarpush.segments.getCount(segment.id);Campaigns
// Create campaign
const campaign = await roarpush.campaigns.create({
name: 'Welcome Series',
template_id: 123,
target_type: 'segment',
target_segment_id: 456,
scheduled_at: '2024-01-20T09:00:00Z',
});
// Get metrics
const metrics = await roarpush.campaigns.getMetrics(campaign.id, {
start_date: '2024-01-01',
end_date: '2024-01-31',
group_by: 'day',
});
// Pause/Resume
await roarpush.campaigns.pause(campaign.id);
await roarpush.campaigns.resume(campaign.id);Automations
// Create automation
const automation = await roarpush.automations.create({
name: 'Welcome Flow',
trigger: {
type: 'event',
event_name: 'user_registered',
},
steps: [
{
id: 'step-1',
type: 'send_notification',
config: { template_id: 123, channels: ['push'] },
next_step_id: 'step-2',
},
{
id: 'step-2',
type: 'delay',
config: { delay_amount: 24, delay_unit: 'hours' },
next_step_id: 'step-3',
},
{
id: 'step-3',
type: 'send_notification',
config: { template_id: 456, channels: ['email'] },
},
],
});
// Activate
await roarpush.automations.activate(automation.id);
// Test entry
await roarpush.automations.testEntry(automation.id, {
external_user_id: 'user-123',
});Bulk Import
// Import audiences from JSON
const job = await roarpush.bulkImport.importAudiences({
audiences: [
{ external_user_id: 'user-1', email: '[email protected]' },
{ external_user_id: 'user-2', email: '[email protected]' },
// ... thousands more
],
options: {
update_existing: true,
skip_invalid: true,
},
});
// Wait for completion
const completed = await roarpush.bulkImport.waitForCompletion(job.job_id);
console.log(`Imported: ${completed.success_count}, Errors: ${completed.error_count}`);
// Import from file
const fileJob = await roarpush.bulkImport.importAudiencesFile(
fileBuffer,
'users.csv',
{ update_existing: true }
);Analytics
// Dashboard overview
const dashboard = await roarpush.analytics.getDashboard({
start_date: '2024-01-01',
end_date: '2024-01-31',
compare_previous: true,
});
// Time series data
const timeSeries = await roarpush.analytics.getTimeSeries({
start_date: '2024-01-01',
end_date: '2024-01-31',
granularity: 'day',
channels: ['push', 'in_app'],
});
// Export to CSV
const downloadUrl = await roarpush.analytics.exportAndWait({
type: 'notifications',
start_date: '2024-01-01',
end_date: '2024-01-31',
format: 'csv',
});Error Handling
import {
RoarPushError,
AuthenticationError,
RateLimitError,
ValidationFailedError,
NotFoundError,
} from '@roarpush/node-sdk';
try {
await roarpush.notifications.send({...});
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfterMs}ms`);
} else if (error instanceof ValidationFailedError) {
console.log('Validation errors:', error.errors);
} else if (error instanceof NotFoundError) {
console.log(`Resource not found: ${error.resourceType}/${error.resourceId}`);
} else if (error instanceof RoarPushError) {
console.log(`API error: ${error.code} - ${error.message}`);
}
}Admin Operations
import { createAdminClient } from '@roarpush/node-sdk';
// Login and get access token
const roarpush = new RoarPush({ apiKey: 'temp-key' });
const { access_token } = await roarpush.adminAuth.login({
email: '[email protected]',
password: 'password',
});
// Create admin client with access token
const admin = createAdminClient(access_token);
// Manage admin users
await admin.adminUsers.create({
email: '[email protected]',
password: 'secure-password',
role: 'admin',
});
// Manage API keys
const { api_key, key } = await admin.apiKeys.create({
name: 'Production Key',
scopes: ['notifications:send', 'audiences:read'],
});
console.log(`Save this key: ${key}`); // Only shown once!
// Manage roles
await admin.roles.create({
name: 'Campaign Manager',
permission_ids: [1, 2, 3],
});TypeScript
Full TypeScript support with comprehensive type definitions:
import type {
Audience,
CreateAudienceInput,
NotificationJob,
CreateNotificationJobInput,
Campaign,
Segment,
PaginatedResponse,
} from '@roarpush/node-sdk';
// Types are inferred automatically
const audience: Audience = await roarpush.audiences.get(123);
// Input types for better IDE support
const input: CreateNotificationJobInput = {
target_type: 'segment',
segment_id: 456,
title: 'Hello',
body: 'World',
};Requirements
- Node.js >= 18.0.0
- TypeScript >= 5.0.0 (optional, for TypeScript users)
License
MIT
