@@ -147,24 +147,39 @@ bedrock.events.on('bedrock.start', async () => {
147147 next ( ) ;
148148 } ) ;
149149
150- // add express compatibility layer to fastify; this translates the express
151- // API to fastify's
152- await fastify . register ( fastifyExpress ) ;
150+ // capture express hooks added by `fastify-express` so they can be made
151+ // conditional (based on whether any fastify routes take precedence)
152+ const originalAddHook = fastify . addHook ;
153+ const capturedHooks = [ ] ;
154+ fastify . addHook = function ( ...args ) {
155+ const [ name , fn ] = args ;
156+ if ( name === 'captureHook' ) {
157+ capturedHooks . push ( fn ) ;
158+ return this ;
159+ }
160+ return Reflect . apply ( originalAddHook , this , args ) ;
161+ } ;
162+ await fastify . register ( fastifyExpress , { expressHook : 'captureHook' } ) ;
163+
164+ // now register captured hooks, but only run them when there is no defined
165+ // fastify route, ensuring express only runs as a fallback
166+ for ( const fn of capturedHooks ) {
167+ fastify . addHook ( 'onRequest' , function expressFallback ( req , reply , next ) {
168+ // only run express as a fallback when no fastify route has been defined
169+ // to handle the request
170+ if ( req . routeOptions . url === undefined ) {
171+ return Reflect . apply ( fn , this , [ req , reply , next ] ) ;
172+ }
173+ next ( ) ;
174+ } ) ;
175+ }
153176
154177 // if server is native http2, add http2 support to fastify express app,
155178 // otherwise (e.g., `spdy` is used) this is unnecessary
156179 if ( isNativeHttp2 ) {
157180 _addHttp2Support ( fastify . express ) ;
158181 }
159182
160- // ensure `request` and `reply` raw values are restored after express runs
161- fastify . addHook ( 'onRequest' , async ( request , reply ) => {
162- const app = request . raw . app ;
163- request . raw = app . request ;
164- reply . raw = app . response ;
165- request . raw . app = reply . raw . app = app ;
166- } ) ;
167-
168183 // init
169184 await bedrock . events . emit ( 'bedrock-express.fastify.init' , { fastify, app} ) ;
170185 await bedrock . events . emit ( 'bedrock-express.init' , app ) ;
0 commit comments