@chord-ts/rpc
Version:
💎 Cutting edge transport framework vanishing borders between frontend and backend
70 lines (69 loc) • 2.4 kB
JavaScript
;
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, {
headers: { 'Content-Type': 'application/json' },
method: 'POST', body: format.stringify(body), ...opt
})
.then(r => format.parse(r))
.catch((e) => {
return { error: e };
});
};
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({ name, data, code, message, reason }) {
super(message);
this.name = name ?? 'RPC Error';
this.data = data;
this.code = code;
this.reason = reason;
}
}
const defaultOnError = async (e, { method, params }) => {
if (!Array.isArray(params))
params = [params];
console.error(`Error occurred during RPC Call: ${method}(${params.map((p) => {
try {
return JSON.stringify(p);
}
catch (e) {
return p;
}
}).join(',')})`);
throw new RPCError(e);
};
exports.defaultOnError = defaultOnError;