khanya-offline-sync
v1.0.0
Published
A Node.js library to manage offline queues and sync with an API, with retry limits and event hooks.
Maintainers
Readme
Khanya Offline Sync
A Node.js library to manage offline queues and sync with an API.
Supports retry limits, custom storage paths, and event hooks.
Installation
npm install khanya-offline-sync
# or
yarn add khanya-offline-syncUsage
const { OfflineSync } = require('khanya-offline-sync');
// Example API call function
async function fakeApiCall(data) {
// Simulate random API success/failure
if (Math.random() < 0.3) throw new Error('Simulated API error');
await new Promise((res) => setTimeout(res, 300));
console.log('API called with:', data);
}
// Initialize OfflineSync
const sync = new OfflineSync(fakeApiCall, {
retryLimit: 5,
storagePath: './myQueue.json'
});
// Listen to events
sync.on('onSyncStart', (queue) => console.log('🔔 Sync started:', queue));
sync.on('onSyncComplete', (queue) =>
console.log('🔔 Sync completed. Remaining queue:', queue)
);
sync.on('onError', (item, err) =>
console.log('🔔 Error syncing item:', item, err.message)
);
// Add items
sync.addToQueue({ msg: 'Hello Node 1' });
sync.addToQueue({ msg: 'Hello Node 2' });
// Check queue and status
console.log('Current queue:', sync.getQueue());
console.log('Status:', sync.getStatus());
// Sync queue
(async () => {
await sync.syncQueue();
console.log('Final queue:', sync.getQueue());
console.log('Status:', sync.getStatus());
})();
API
new OfflineSync(apiCallFunction, options)
apiCallFunction: Async function to call the API.options: Configuration object.
Methods
addToQueue(item): Add an item to the queue.getQueue(): Get the current queue.getStatus(): Get the sync statussyncQueue(): Manually trigger sync of the queue.
Events
onSyncStart(queue): Emitted when sync starts.onSyncComplete(queue): Emitted when sync completes.onError(item, error): Emitted on sync error for an item.
License
MIT © Khanyakwezwe
