@@ -50,13 +50,15 @@ class Client {
5050 res . end ( ) ;
5151 }
5252
53- error ( status , err ) {
53+ error ( status , err , callId = err ) {
5454 const { req : { url } , res, connection } = this ;
5555 const reason = http . STATUS_CODES [ status ] ;
56+ if ( typeof err === 'number' ) err = undefined ;
5657 const error = err ? err . stack : reason ;
5758 const msg = status === 403 ? err . message : `${ url } - ${ error } - ${ status } ` ;
5859 application . logger . error ( msg ) ;
59- const result = JSON . stringify ( { result : 'error' , reason } ) ;
60+ const packet = { callback : callId , error : { message : reason } } ;
61+ const result = JSON . stringify ( packet ) ;
6062 if ( connection ) {
6163 connection . send ( result ) ;
6264 return ;
@@ -66,36 +68,45 @@ class Client {
6668 res . end ( result ) ;
6769 }
6870
69- async rpc ( method , args ) {
71+ message ( data ) {
72+ const packet = JSON . parse ( data ) ;
73+ const [ callType , methodName ] = Object . keys ( packet ) ;
74+ const callId = packet [ callType ] ;
75+ const args = packet [ methodName ] ;
76+ this . rpc ( callId , methodName , args ) ;
77+ }
78+
79+ async rpc ( callId , method , args ) {
7080 const { res, connection } = this ;
7181 const { semaphore } = application . server ;
7282 try {
7383 await semaphore . enter ( ) ;
7484 } catch {
75- this . error ( 504 ) ;
85+ this . error ( 504 , callId ) ;
7686 return ;
7787 }
7888 try {
7989 const session = await application . auth . restore ( this ) ;
8090 const proc = application . runMethod ( method , session ) ;
8191 if ( ! proc ) {
82- this . error ( 404 ) ;
92+ this . error ( 404 , callId ) ;
8393 return ;
8494 }
8595 if ( ! session && proc . access !== 'public' ) {
86- this . error ( 403 , new Error ( `Forbidden: /api/${ method } ` ) ) ;
96+ this . error ( 403 , new Error ( `Forbidden: /api/${ method } ` ) , callId ) ;
8797 return ;
8898 }
8999 const result = await proc . method ( args ) ;
90100 if ( ! session && proc . access === 'public' ) {
91101 const session = application . auth . start ( this , result . userId ) ;
92102 result . token = session . token ;
93103 }
94- const data = JSON . stringify ( result ) ;
104+ const packet = { callback : callId , result } ;
105+ const data = JSON . stringify ( packet ) ;
95106 if ( connection ) connection . send ( data ) ;
96107 else res . end ( data ) ;
97108 } catch ( err ) {
98- this . error ( 500 , err ) ;
109+ this . error ( 500 , err , callId ) ;
99110 } finally {
100111 semaphore . leave ( ) ;
101112 }
0 commit comments