import pathToRegexp = require ( 'path-to-regexp' ) ; import { RequestStartMiddleware } from '../../filter' ; import { RouteNotFoundException } from '../exceptions' ; import { Response , Request } from '../../types' ; import { IRouteTable } from '../../interfaces' ; Throws export class RouteNotFoundMiddleware extends RequestStartMiddleware { private routes : RegExp [ ] = [ ] ; private isRouteTableLoaded = false ; constructor ( private routeTable ) { super ( ) ; } invoke ( request , response , next ) { if ( this . isRouteTableLoaded === false ) { let routes = this . routeTable . getRoutes ( ) ; for ( const route of routes ) { this . routes . push ( pathToRegexp ( route ) ) ; } this . isRouteTableLoaded = true ; } let requestUrl = `/${ request . method }_${ request . baseUrl }${ request . path }` . toLowerCase ( ) ; let isRouteMatched = false ; for ( const route of this . routes ) { if ( route . test ( requestUrl ) ) { isRouteMatched = true ; break ; } } if ( isRouteMatched ) { next ( ) ; } else { next ( new RouteNotFoundException ( request . method , `${ request . baseUrl }${ request . path }` ) ) ; } } }