UNPKG

@rsweeten/dropbox-sync

Version:

Reusable Dropbox synchronization module with framework adapters

63 lines (62 loc) 1.74 kB
import { io } from 'socket.io-client'; export function createSocketMethods() { let socket = null; const handlers = {}; return { /** * Establish a Socket.IO connection */ connect() { if (!socket) { // Default connection to the server's base URL const url = globalThis?.window?.location?.origin || 'http://localhost:3000'; socket = io(url); } if (socket && !socket.connected) { socket.connect(); } }, /** * Disconnect the Socket.IO connection */ disconnect() { if (socket && socket.connected) { socket.disconnect(); } }, /** * Listen for an event on the Socket.IO connection */ on(event, handler) { if (!handlers[event]) { handlers[event] = []; } handlers[event].push(handler); if (socket) { socket.on(event, handler); } }, /** * Remove listeners for an event on the Socket.IO connection */ off(event) { if (socket && handlers[event]) { for (const handler of handlers[event]) { socket.off(event, handler); } delete handlers[event]; } }, /** * Emit an event on the Socket.IO connection */ emit(event, ...args) { if (socket) { socket.emit(event, ...args); return true; } return false; }, }; }