rpc-websocketserver
Version:
Simple rpc websocket server, wrapping the very popular 'ws' library. Register your RPCs with convenient decorators.
56 lines • 2.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertValidJSONRPC2Request = exports.buildResponse = exports.buildError = void 0;
var utils_1 = require("../utils");
var ERRORS = new Map([
[-32600, 'Invalid Request'],
[-32601, 'Method not found'],
[-32602, 'Invalid params'],
[-32603, 'Internal error'],
[-32604, 'Params not found'],
[-32700, 'Parse error'],
]);
/**
* Builds and returns a JSON RPC 2 conform error object.
*
* @param code {number} - JSON RPC 2 error code
* @param details {ErrorDetails} - optional primitive or structured value with detailed error information
*/
function buildError(code, details) {
var error = { code: code, message: ERRORS.get(code) || 'Internal server error' };
if (details)
error.data = details;
return error;
}
exports.buildError = buildError;
/**
* Builds and returns a JSON RPC 2 conform response object.
*
* @param error {boolean} - if true -> builds JSON RPC 2 error response, if false -> JSON RPC 2 result response
* @param id {Id} - JSON RPC 2 id
* @param data {any | ErrorObject} - should be rpc result if error is false, otherwise ErrorObject
*/
function buildResponse(error, id, data) {
if (error)
return { jsonrpc: '2.0', error: data, id: id };
return { jsonrpc: '2.0', result: data, id: id };
}
exports.buildResponse = buildResponse;
/**
* Assertion to ensure value is a JSON RPC 2 conform request
*
* @param val {*} - value to be asserted on
* @param Err {ErrorType} - Error to be thrown if assertion fails
*/
function assertValidJSONRPC2Request(val, Err) {
if ((val === null || val === void 0 ? void 0 : val.jsonrpc) !== '2.0')
throw new Err("Value of 'jsonrpc' must be exactly '2.0' and of type 'string'");
if (val.hasOwnProperty('id')) {
if (typeof val.id !== 'string' && typeof val.id !== 'number' && val.id !== null) {
throw new Err("Value of 'id' should be of type 'string' or 'number'");
}
}
utils_1.assertValidRequest(val, Err);
}
exports.assertValidJSONRPC2Request = assertValidJSONRPC2Request;
//# sourceMappingURL=utils.js.map