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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | 1x 1x 9x 6x 7x 1x 1x 6x 6x 4x 2x 2x 1x 1x 2x 4x 3x 9x 9x 9x 9x 9x 2x 1x 1x 2x 7x 6x 1x 8x 1x 1x | import {Transport} from './Transport';
import {
ParseRPCMessage,
RPCMessage,
RPCRequest,
RPCResponse,
RPCResponseError,
RPCResponseResult,
JSONParseError,
InvalidMessageError,
InvalidRequestError
} from './Message';
import { RPCMethodError } from './Defines';
import { clearTimeout } from 'timers';
declare type MethodHandler = (...args: any[]) => any;
interface MethodHandlerMap
{
[index: string]: MethodHandler;
}
abstract class RPCServerBase
{
// Holds all binded server methods
handlers: MethodHandlerMap = {};
bind(name: string, handler: MethodHandler)
{
this.handlers[name] = handler;
}
async handleRequest(req: RPCRequest)
{
if (this.handlers[req.method] === undefined) {
this.send(new RPCResponseError(req.id, {
code: -32601,
message: 'Method not found'
}));
return;
}
try {
// Expand arguments if it is array
if (req.params instanceof Array)
var result = await this.handlers[req.method](...req.params);
else
var result = await this.handlers[req.method](req.params);
} catch (e) {
// Send a custom error
if (e instanceof RPCMethodError) {
this.send(new RPCResponseError(req.id, {
code: e.code,
message: e.message,
data: e.data
}));
}
// Send internal server error
else {
this.send(new RPCResponseError(req.id, {
code: -32603,
message: e.name + ': ' + e.message,
}));
}
return;
}
// Do not send result if request was notification
if (!req.isNotification())
this.send(new RPCResponseResult(req.id, result));
}
abstract send(msg: RPCMessage): void;
}
class RPCServer extends RPCServerBase
{
// Handles communications
private transport: Transport;
constructor(transport: Transport) {
super();
this.transport = transport;
this.transport.SetDownstreamCb((data: string) => this.parseMessage(data));
}
parseMessage(data: string)
{
try {
var message = ParseRPCMessage(data);
} catch (e) {
if (e instanceof JSONParseError) {
this.send(new RPCResponseError(null, {
code: -32700,
message: 'Parse error',
}));
} else {
this.send(new RPCResponseError(null, {
code: -32600,
message: 'Invalid Request',
}));
}
return;
}
if (message instanceof RPCRequest)
this.handleRequest(message);
else {
this.send(new RPCResponseError(null, {
code: -32600,
message: 'Invalid Request',
}));
}
}
send(msg: RPCMessage): void
{
this.transport.SendUpstream(JSON.stringify(msg));
}
}
export {
MethodHandler,
MethodHandlerMap,
RPCServerBase,
RPCServer
};
|