import { DEFAULT_MESSAGE_ENCODING_FORMAT } from './constants' ; import { RPCResponseAlreadySentError } from './errors' ; import { P2PResponsePacket , RequestOptions } from './types' ; export class P2PRequest { private readonly _procedure : string ; private readonly _data : Buffer | undefined ; private readonly _respondCallback : ( responseError ? : Error , responseData ? : P2PResponsePacket ) => void ; private readonly _peerId : string ; private _wasResponseSent : boolean ; private readonly _rate : number ; public constructor ( options , respondCallback ) { this . _procedure = options . procedure ; this . _data = this . _getBufferData ( options ) ; this . _peerId = options . id ; this . _rate = options . rate ; options . productivity . requestCounter += 1 ; this . _respondCallback = ( responseError ? , responsePacket ? ) : void => { if ( this . _wasResponseSent ) { throw new RPCResponseAlreadySentError ( `A response has already been sent for the request procedure <<${ options . procedure }>>` ) ; } this . _wasResponseSent = true ; if ( ! responseError && responsePacket ) { options . productivity . lastResponded = Date . now ( ) ; options . productivity . responseCounter += 1 ; } options . productivity . responseRate = options . productivity . responseCounter / options . productivity . requestCounter ; respondCallback ( responseError , responsePacket ) ; } ; this . _wasResponseSent = false ; } public get procedure ( ) : string { return this . _procedure ; } public get data ( ) : Buffer | undefined { return this . _data ; } public get rate ( ) : number { return this . _rate ; } public get peerId ( ) : string { return this . _peerId ; } public get wasResponseSent ( ) : boolean { return this . _wasResponseSent ; } public end ( responseData ? ) { const data = this . _getBase64Data ( responseData ) ; const responsePacket = { data , peerId : this . peerId , } ; this . _respondCallback ( undefined , responsePacket ) ; } public error ( responseError ) { this . _respondCallback ( responseError ) ; } private _getBase64Data ( data ) { if ( ! data ) { return undefined ; } if ( Buffer . isBuffer ( data ) ) { return data . toString ( DEFAULT_MESSAGE_ENCODING_FORMAT ) ; } return Buffer . from ( JSON . stringify ( data ) , 'utf8' ) . toString ( DEFAULT_MESSAGE_ENCODING_FORMAT ) ; } private _getBufferData ( options ) { return typeof options . data === 'string' ? Buffer . from ( options . data , DEFAULT_MESSAGE_ENCODING_FORMAT ) : undefined ; } }