All files RPCNode.ts

100% Statements 27/27
100% Branches 4/4
100% Functions 7/7
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 791x 1x   1x           1x 1x       1x 2x 7x 5x                   3x 3x 3x               3x                   3x 3x 3x           3x 3x   1x 1x     2x 1x   1x         2x     1x     1x    
import { RequestMap, RPCClientBase } from './RPCClient';
import { MethodHandler, MethodHandlerMap, RPCServerBase } from './RPCServer';
import { Transport } from './Transport';
import {
    ParseRPCMessage,
    RPCMessage,
    RPCRequest,
    RPCResponse,
} from './Message';
import { EventEmitter } from 'events';
import { JSONRPC_TIMEOUT } from './Defines';
 
// Hack for multiple inheritance
function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            if (name !== 'constructor') {
                derivedCtor.prototype[name] = baseCtor.prototype[name];
            }
        });
    }); 
}
 
class RPCNode extends EventEmitter implements RPCClientBase, RPCServerBase
{
    // Hacks to achieve multiple inheritance
    // RPCClientBase
    requestId: number = 0;
    requests: RequestMap = {};
    requestTimeout: number = JSONRPC_TIMEOUT;
    /* istanbul ignore next */
    call(name: string, ...params: any[]) { return new Promise((res, rej) => {}); };
    /* istanbul ignore next */
    notify(name: string, ...params: any[]) {};
    /* istanbul ignore next */
    handleResponse(res: RPCResponse) {};
    // RPCServerBase
    handlers: MethodHandlerMap = {};
    /* istanbul ignore next */
    bind(name: string, handler: MethodHandler) {};
    /* istanbul ignore next */
    async handleRequest(req: RPCRequest) {};
 
    // Handles communications
    private transport: Transport;
 
    constructor(transport: Transport) {
        super();
        this.transport = transport;
        this.transport.SetDownstreamCb((data: string) => this.parseMessage(data));
    }
 
    // Parses received string and handles as request or response
    parseMessage(data: string)
    {
        try {
            var message = ParseRPCMessage(data);
        } catch (e) {
            this.emit('error', new Error(`Message parse failed: ${e.message}`));
            return;
        }
 
        if (message.isResponse())
            this.handleResponse(<RPCResponse>message);
        else
            this.handleRequest(<RPCRequest>message);
    }
 
    send(msg: RPCMessage): void
    {
        this.transport.SendUpstream(JSON.stringify(msg));
    }
}
applyMixins(RPCNode, [RPCClientBase, RPCServerBase]);
 
export {
    RPCNode
}