@@ -81,44 +81,43 @@ class Client {
8181 res . end ( result ) ;
8282 }
8383
84- async execute ( method , args ) {
85- const { application } = this ;
84+ async rpc ( method , args ) {
85+ const { application, res , connection } = this ;
8686 const { semaphore } = application . server ;
87- await semaphore . enter ( ) ;
87+ try {
88+ await semaphore . enter ( ) ;
89+ } catch {
90+ this . error ( 504 ) ;
91+ return ;
92+ }
8893 try {
8994 const session = await application . auth . restore ( this ) ;
9095 const sandbox = session ? session . sandbox : undefined ;
9196 const context = session ? session . context : { } ;
9297 const exp = application . runScript ( method , sandbox ) ;
98+ if ( ! exp ) {
99+ this . error ( 404 ) ;
100+ return ;
101+ }
93102 const proc = exp ( context ) ;
94103 if ( ! session && proc . access !== 'public' ) {
95- semaphore . leave ( ) ;
96- throw new Error ( `Forbidden: /api/ ${ method } ` ) ;
104+ this . error ( 403 , new Error ( `Forbidden: /api/ ${ method } ` ) ) ;
105+ return ;
97106 }
98107 const result = await proc . method ( args ) ;
99108 if ( ! session && proc . access === 'public' ) {
100109 const session = application . auth . start ( this , result . userId ) ;
101110 result . token = session . token ;
102111 }
103- return JSON . stringify ( result ) ;
112+ const data = JSON . stringify ( result ) ;
113+ if ( connection ) connection . send ( data ) ;
114+ else res . end ( data ) ;
115+ } catch ( err ) {
116+ this . error ( 500 , err ) ;
104117 } finally {
105118 semaphore . leave ( ) ;
106119 }
107120 }
108-
109- async rpc ( method , args ) {
110- const { res, connection } = this ;
111- try {
112- const result = await this . execute ( method , args ) ;
113- if ( connection ) connection . send ( result ) ;
114- else res . end ( result ) ;
115- } catch ( err ) {
116- if ( err . message === 'Not found' ) this . error ( 404 ) ;
117- else if ( err . message === 'Semaphore timeout' ) this . error ( 504 ) ;
118- else if ( err . message . startsWith ( 'Forbidden:' ) ) this . error ( 403 , err ) ;
119- else this . error ( 500 , err ) ;
120- }
121- }
122121}
123122
124123const listener = application => ( req , res ) => {
0 commit comments