picorpc
Version:
A tiny RPC library and spec, inspired by JSON-RPC 2.0 and tRPC.
73 lines (72 loc) • 2.06 kB
JavaScript
/* MAIN */
const attempt = (fn, fallback) => {
try {
return fn();
}
catch {
return fallback;
}
};
const castError = (exception) => {
if (isError(exception))
return exception;
if (isString(exception))
return new Error(exception);
return new Error('Unknown error');
};
const identity = (value) => {
return value;
};
const isArray = (value) => {
return Array.isArray(value);
};
const isError = (value) => {
return value instanceof Error;
};
const isFinite = (value) => {
return typeof value === 'number' && Number.isFinite(value);
};
const isFunction = (value) => {
return typeof value === 'function';
};
const isInteger = (value) => {
return typeof value === 'number' && Number.isInteger(value);
};
const isNumber = (value) => {
return typeof value === 'number';
};
const isObject = (value) => {
return typeof value === 'object' && value !== null;
};
const isString = (value) => {
return typeof value === 'string';
};
const isUndefined = (value) => {
return typeof value === 'undefined';
};
const isVersionCompatible = (version, supported) => {
const parse = (version) => {
const [major, minor, patch] = version.split('.').map(Number);
const valid = [major, minor, patch].every(isFinite);
return { major, minor, patch, valid };
};
const v = parse(version);
const s = parse(supported);
if (!v.valid || !s.valid)
return false; // Invalid version(s)
if (v.major !== s.major)
return false; // Incompatible major version
if (v.minor > s.minor)
return false; // Incompatible minor version
if (v.minor === s.minor && v.patch > s.patch)
return false; // Incompatible patch version
return true;
};
const noop = () => {
return;
};
const rethrow = (exception) => {
throw exception;
};
/* EXPORT */
export { attempt, castError, identity, isArray, isError, isFinite, isFunction, isInteger, isNumber, isObject, isString, isUndefined, isVersionCompatible, noop, rethrow };