UNPKG

prostgles-client

Version:

Reactive client for Postgres

81 lines (80 loc) 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useProstglesClient = exports.getIO = void 0; const prostgles_1 = require("../prostgles"); const SyncedTable_1 = require("../SyncedTable/SyncedTable"); const reactImports_1 = require("./reactImports"); const useAsyncEffectQueue_1 = require("./useAsyncEffectQueue"); const useIsMounted_1 = require("./useIsMounted"); const getIO = (throwError = false) => { try { // eslint-disable-next-line @typescript-eslint/no-require-imports const io = require("socket.io-client"); return io; } catch (err) { } if (throwError) throw new Error("Must install socket.io-client"); return {}; }; exports.getIO = getIO; const useProstglesClient = ({ skip, socketOptions: socketPathOrOptions, endpoint, token, ...initOpts } = {}) => { const { useRef, useState } = (0, reactImports_1.getReact)(true); const [onReadyArgs, setOnReadyArgs] = useState({ isLoading: true, hasError: false, }); const getIsMounted = (0, useIsMounted_1.useIsMounted)(); const socketRef = useRef(); (0, useAsyncEffectQueue_1.useAsyncEffectQueue)(async () => { var _a, _b; if (skip) return undefined; (_a = socketRef.current) === null || _a === void 0 ? void 0 : _a.disconnect(); const io = (0, exports.getIO)(); const socketOptions = typeof socketPathOrOptions === "string" ? { path: socketPathOrOptions } : socketPathOrOptions; const socketOptionsWithDefaults = { withCredentials: initOpts.credentials && initOpts.credentials !== "omit", ...socketOptions, reconnectionDelay: 1000, reconnection: true, }; (_b = socketOptionsWithDefaults.path) !== null && _b !== void 0 ? _b : (socketOptionsWithDefaults.path = `/ws-api`); if (token) { socketOptionsWithDefaults.auth = { token }; } const socket = endpoint ? io(endpoint, socketOptionsWithDefaults) : io(socketOptionsWithDefaults); socketRef.current = socket; await (0, prostgles_1.prostgles)({ socket, endpoint, ...initOpts, onReady: (onReadyArgs) => { var _a, _b; if (!getIsMounted()) { (_a = initOpts.onDebug) === null || _a === void 0 ? void 0 : _a.call(initOpts, { type: "onReady.notMounted", data: onReadyArgs, }); return; } (_b = initOpts.onDebug) === null || _b === void 0 ? void 0 : _b.call(initOpts, { type: "onReady", data: onReadyArgs }); setOnReadyArgs({ ...onReadyArgs, hasError: false, isLoading: false }); }, }, SyncedTable_1.SyncedTable).catch((error) => { if (!getIsMounted()) return; setOnReadyArgs({ isLoading: false, error, hasError: true }); }); return () => { socket.disconnect(); socket.emit = () => { throw "Socket disconnected"; }; }; }, [initOpts, socketPathOrOptions, skip], 80); return onReadyArgs; }; exports.useProstglesClient = useProstglesClient;