33/**
44 * Lightweight web framework for your serverless applications
55 * @author Jeremy Daly <jeremy@jeremydaly.com>
6- * @version 0.5.0
6+ * @version 0.5.1
77 * @license MIT
88 */
99
@@ -47,6 +47,9 @@ class API {
4747 // Keep track of callback execution
4848 this . _done = false
4949
50+ // Keep track of triggered errors
51+ this . _error = false
52+
5053 // Executed after the callback
5154 this . _finally = ( ) => { }
5255
@@ -115,6 +118,8 @@ class API {
115118 this . _event = event
116119 this . _context = context
117120 this . _cb = cb
121+ this . _done = false
122+ this . _error = false
118123
119124 try {
120125 // Initalize response and request objects
@@ -123,11 +128,13 @@ class API {
123128
124129 // Loop through the middleware and await response
125130 for ( const mw of this . _middleware ) {
131+ if ( this . _done || this . _error ) break
132+ // Promisify middleware
126133 await new Promise ( r => { mw ( this . request , this . response , ( ) => { r ( ) } ) } )
127134 } // end for
128135
129136 // Execute the primary handler
130- await this . handler ( this . request , this . response )
137+ if ( ! this . _done && ! this . _error ) await this . handler ( this . request , this . response )
131138
132139 } catch ( e ) {
133140 this . catchErrors ( e )
@@ -157,13 +164,22 @@ class API {
157164 ! this . _test && console . log ( 'API Error:' , e )
158165 }
159166
160- // Execute error middleware
161- for ( const err of this . _errors ) {
162- // Promisify error middleware
163- await new Promise ( r => { err ( e , this . request , this . response , ( ) => { r ( ) } ) } )
164- } // end for
167+ // If first time through, process error middleware
168+ if ( ! this . _error ) {
165169
166- this . response . json ( { 'error' :message } )
170+ // Flag error state (this will avoid infinite error loops)
171+ this . _error = true
172+
173+ // Execute error middleware
174+ for ( const err of this . _errors ) {
175+ if ( this . _done ) break
176+ // Promisify error middleware
177+ await new Promise ( r => { err ( e , this . request , this . response , ( ) => { r ( ) } ) } )
178+ } // end for
179+ }
180+
181+ // Throw standard error unless callback has already been executed
182+ if ( ! this . _done ) this . response . json ( { 'error' :message } )
167183
168184 } // end catch
169185
@@ -172,6 +188,9 @@ class API {
172188 // Custom callback
173189 async _callback ( err , res ) {
174190
191+ // Set done status
192+ this . _done = true
193+
175194 // Execute finally
176195 await this . _finally ( this . request , this . response )
177196
0 commit comments