UNPKG

picorpc

Version:

A tiny RPC library and spec, inspired by JSON-RPC 2.0 and tRPC.

37 lines (36 loc) 1.2 kB
/* IMPORT */ import { ERROR_CODE_FAILED_PROCEDURE_EXEC, ERROR_MESS_FAILED_PROCEDURE_EXEC } from '../constants.js'; import Error from './error.js'; import { identity, rethrow } from '../utils.js'; /* MAIN */ class Request { /* CONSTRUCTOR */ constructor(handler, request) { this.handler = handler; this.request = request; } /* API */ exec() { return this.then(); } then(onSuccess = identity, onError = rethrow) { return this.handler(this.request).then(_response => { const response = _response.valueOf(); if ('error' in response) { // Error response const code = response.error.code || ERROR_CODE_FAILED_PROCEDURE_EXEC; const message = response.error.message || ERROR_MESS_FAILED_PROCEDURE_EXEC; const data = response.error.data; const error = new Error(code, message, data); throw error; } else { // Success response return response.result; //TSC } }).then(onSuccess, onError); } valueOf() { return this.request; } } /* EXPORT */ export default Request;