UNPKG

@chord-ts/rpc

Version:

💎 Cutting edge transport framework vanishing borders between frontend and backend

59 lines (58 loc) • 2.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultOnError = exports.defaultCache = exports.defaultTransport = void 0; const defaultTransport = async ({ route, body, format }, opt) => { return await fetch(route, { method: 'POST', body: format.stringify(body), ...opt }) .then(r => format.parse(r)) .catch(() => { return { error: { message: 'Failed during fetch request' } }; }); }; exports.defaultTransport = defaultTransport; const defaultCache = (config) => { const storageKey = '__chord_cache__'; const expiry = config?.expiry ?? 1000 * 60 * 5; const onInvalidate = config?.onInvalidate ?? (() => { }); function call2Key(method, params) { return `${method}(${JSON.stringify(params)})`; } const get = ({ method, params }) => { if (typeof localStorage === 'undefined') return null; const store = JSON.parse(localStorage.getItem(storageKey) ?? '{}'); const callKey = call2Key(method, params); const cached = store[callKey]; if (!cached) return null; if (Date.now() - Date.parse(cached?.time) > expiry) { return null; } return cached?.result; }; const set = ({ method, params }, result) => { if (typeof localStorage === 'undefined') return null; const store = JSON.parse(localStorage.getItem(storageKey) ?? '{}'); const callKey = call2Key(method, params); store[callKey] = { result, time: new Date() }; onInvalidate(result); localStorage.setItem(storageKey, JSON.stringify(store)); }; return { get, set }; }; exports.defaultCache = defaultCache; class RPCError extends Error { constructor({ data, code, message }) { super(message); this.name = 'RPC Error'; this.data = data; this.code = code; } } const defaultOnError = async (e, { method, params }) => { if (!Array.isArray(params)) params = [params]; console.error(`Error occurred during RPC Call: ${method}(${params.map((p) => JSON.stringify(p)).join(',')})`); throw new RPCError(e); }; exports.defaultOnError = defaultOnError;