This example demonstrates how to migrate from PubNub to OddSockets with minimal code changes using our PubNub compatibility layer. Most existing PubNub code will work unchanged!
The cluster reroutes you if a node goes away, and the SDK reconnects and resubscribes
Transparent pricing without message-based charges
Split anything larger, or publish a reference to it
Comprehensive analytics and monitoring included
Per-message TTL, custom metadata and retained history
The compatibility layer keeps your existing call shapes; you swap the keys
const { PubNubCompat } = require('../src/index');
/**
* PubNub to OddSockets Migration Example
*
* This example shows how to migrate from PubNub to OddSockets with minimal code changes.
* The PubNubCompat class provides a drop-in replacement for PubNub's JavaScript SDK.
*/
async function migrationExample() {
console.log('š PubNub to OddSockets Migration Example');
// BEFORE: PubNub configuration
// const pubnub = new PubNub({
// publishKey: 'pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
// subscribeKey: 'sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
// userId: 'user123'
// });
// AFTER: OddSockets with PubNub compatibility
const pubnub = new PubNubCompat({
publishKey: 'ak_live_1234567890abcdef', // Your OddSockets API key
subscribeKey: 'ak_live_1234567890abcdef', // Same as publishKey for OddSockets
userId: 'user123',
managerUrl: 'https://connect.oddsockets.tyga.network' // Optional: OddSockets manager URL
});
console.log('ā
OddSockets client created with PubNub compatibility');
// Add listeners (same as PubNub)
pubnub.addListener({
status: function(statusEvent) {
console.log('š Status:', statusEvent.category);
if (statusEvent.category === 'PNConnectedCategory') {
console.log('š Connected to OddSockets via PubNub compatibility layer');
}
},
message: function(messageEvent) {
console.log('šØ Message received:', {
channel: messageEvent.channel,
message: messageEvent.message,
publisher: messageEvent.publisher,
timetoken: messageEvent.timetoken
});
},
presence: function(presenceEvent) {
console.log('š¤ Presence event:', {
channel: presenceEvent.channel,
action: presenceEvent.action,
uuid: presenceEvent.uuid,
occupancy: presenceEvent.occupancy
});
}
});
// Subscribe to channels (same as PubNub)
console.log('š” Subscribing to channels...');
pubnub.subscribe({
channels: ['migration-demo', 'chat-room'],
withPresence: true
});
// Wait a moment for connection
await new Promise(resolve => setTimeout(resolve, 2000));
// Publish messages (same as PubNub)
console.log('š¤ Publishing messages...');
// Simple message
await pubnub.publish({
channel: 'migration-demo',
message: 'Hello from OddSockets via PubNub compatibility!'
});
// Message with metadata
await pubnub.publish({
channel: 'migration-demo',
message: {
type: 'migration_test',
content: 'This message was sent using PubNub-compatible API',
timestamp: Date.now()
},
meta: {
source: 'migration-example',
version: '1.0'
}
});
console.log('ā
Messages published');
// Get message history (same as PubNub)
console.log('š Fetching message history...');
try {
const historyResponse = await pubnub.history({
channel: 'migration-demo',
count: 10
});
console.log(`š Retrieved ${historyResponse.messages.length} messages from history`);
historyResponse.messages.forEach((msg, index) => {
console.log(` ${index + 1}. ${JSON.stringify(msg[0])} (${new Date(msg[1] / 10000).toISOString()})`);
});
} catch (error) {
console.log('š History not available yet (channel may be new)');
}
// Get presence information (same as PubNub)
console.log('š„ Fetching presence information...');
try {
const presenceResponse = await pubnub.hereNow({
channels: ['migration-demo', 'chat-room']
});
console.log(`š¤ Total occupancy: ${presenceResponse.totalOccupancy} across ${presenceResponse.totalChannels} channels`);
Object.keys(presenceResponse.channels).forEach(channel => {
const channelData = presenceResponse.channels[channel];
console.log(` šŗ ${channel}: ${channelData.occupancy} users`);
});
} catch (error) {
console.log('š„ Presence information not available yet');
}
// Set user state (same as PubNub)
console.log('š Setting user state...');
try {
await pubnub.setState({
channels: ['migration-demo'],
state: {
status: 'migrating',
from: 'pubnub',
to: 'oddsockets',
timestamp: Date.now()
}
});
console.log('ā
User state updated');
} catch (error) {
console.log('š State update not available yet');
}
// Demonstrate additional OddSockets features
console.log('š OddSockets provides:');
console.log(' ⢠No per-message pricing - a monthly message allowance');
console.log(' ⢠32 KB maximum message size');
console.log(' ⢠Per-message TTL and custom metadata');
console.log(' ⢠Retained message history');
console.log(' ⢠Built-in usage analytics');
console.log(' ⢠Automatic failover, reconnect and resubscribe');
// Migration checklist
console.log('\nš Migration Checklist:');
console.log(' ā
Replace PubNub import with OddSockets PubNubCompat');
console.log(' ā
Update publishKey/subscribeKey to OddSockets API key');
console.log(' ā
Add managerUrl configuration (optional)');
console.log(' ā
All existing PubNub code works unchanged');
console.log(' ā
Enjoy better performance and lower costs!');
// Keep running for a bit
console.log('\nā³ Keeping connection alive for 20 seconds...');
setTimeout(() => {
console.log('š Disconnecting...');
pubnub.disconnect();
console.log('ā
Migration example completed successfully!');
console.log('š You\'ve successfully migrated from PubNub to OddSockets!');
process.exit(0);
}, 20000);
}
// Handle errors
process.on('unhandledRejection', (error) => {
console.error('ā Unhandled error:', error);
process.exit(1);
});
// Run the migration example
migrationExample().catch(console.error);