@@ -50,13 +50,15 @@ class Client {
50
50
res . end ( ) ;
51
51
}
52
52
53
- error ( status , err ) {
53
+ error ( status , err , callId = err ) {
54
54
const { req : { url } , res, connection } = this ;
55
55
const reason = http . STATUS_CODES [ status ] ;
56
+ if ( typeof err === 'number' ) err = undefined ;
56
57
const error = err ? err . stack : reason ;
57
58
const msg = status === 403 ? err . message : `${ url } - ${ error } - ${ status } ` ;
58
59
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 ) ;
60
62
if ( connection ) {
61
63
connection . send ( result ) ;
62
64
return ;
@@ -66,36 +68,45 @@ class Client {
66
68
res . end ( result ) ;
67
69
}
68
70
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 ) {
70
80
const { res, connection } = this ;
71
81
const { semaphore } = application . server ;
72
82
try {
73
83
await semaphore . enter ( ) ;
74
84
} catch {
75
- this . error ( 504 ) ;
85
+ this . error ( 504 , callId ) ;
76
86
return ;
77
87
}
78
88
try {
79
89
const session = await application . auth . restore ( this ) ;
80
90
const proc = application . runMethod ( method , session ) ;
81
91
if ( ! proc ) {
82
- this . error ( 404 ) ;
92
+ this . error ( 404 , callId ) ;
83
93
return ;
84
94
}
85
95
if ( ! session && proc . access !== 'public' ) {
86
- this . error ( 403 , new Error ( `Forbidden: /api/${ method } ` ) ) ;
96
+ this . error ( 403 , new Error ( `Forbidden: /api/${ method } ` ) , callId ) ;
87
97
return ;
88
98
}
89
99
const result = await proc . method ( args ) ;
90
100
if ( ! session && proc . access === 'public' ) {
91
101
const session = application . auth . start ( this , result . userId ) ;
92
102
result . token = session . token ;
93
103
}
94
- const data = JSON . stringify ( result ) ;
104
+ const packet = { callback : callId , result } ;
105
+ const data = JSON . stringify ( packet ) ;
95
106
if ( connection ) connection . send ( data ) ;
96
107
else res . end ( data ) ;
97
108
} catch ( err ) {
98
- this . error ( 500 , err ) ;
109
+ this . error ( 500 , err , callId ) ;
99
110
} finally {
100
111
semaphore . leave ( ) ;
101
112
}
0 commit comments