* Extends Req / Res objects, pushes 404 and 500 handlers, dispatches middleware * @param req Req object * @param res Res object
(req: Req, res: Res, next?: NextFunction)
| 251 | * @param res Res object |
| 252 | */ |
| 253 | handler(req: Req, res: Res, next?: NextFunction) { |
| 254 | /* Set X-Powered-By header */ |
| 255 | const { xPoweredBy } = this.settings |
| 256 | if (xPoweredBy) res.setHeader('X-Powered-By', typeof xPoweredBy === 'string' ? xPoweredBy : 'tinyhttp') |
| 257 | |
| 258 | const exts = this.applyExtensions || extendMiddleware<RenderOptions>(this) |
| 259 | |
| 260 | req.originalUrl = req.url || req.originalUrl |
| 261 | |
| 262 | const pathname = getPathname(req.originalUrl) |
| 263 | |
| 264 | const matched = this.find(pathname) |
| 265 | |
| 266 | const mw: Middleware[] = [ |
| 267 | { |
| 268 | handler: exts, |
| 269 | type: 'mw', |
| 270 | path: '/' |
| 271 | }, |
| 272 | ...matched.filter((x) => (x.method ? x.method === req.method : true)) |
| 273 | ] |
| 274 | |
| 275 | if (matched[0] != null) { |
| 276 | mw.push({ |
| 277 | type: 'mw', |
| 278 | handler: (req, res, next) => { |
| 279 | if (req.method === 'HEAD') { |
| 280 | res.statusCode = 204 |
| 281 | return res.end('') |
| 282 | } |
| 283 | next() |
| 284 | }, |
| 285 | path: '/' |
| 286 | }) |
| 287 | } |
| 288 | |
| 289 | mw.push({ |
| 290 | handler: this.noMatchHandler, |
| 291 | type: 'mw', |
| 292 | path: '/' |
| 293 | }) |
| 294 | |
| 295 | const handle = (mw: Middleware) => async (req: Req, res: Res, next?: NextFunction) => { |
| 296 | const { path, handler, type, regex } = mw |
| 297 | |
| 298 | const params = regex ? getURLParams(regex, pathname) : {} |
| 299 | |
| 300 | if (type === 'route') req.params = params |
| 301 | |
| 302 | if (path.includes(':')) { |
| 303 | const url = req.url.slice(req.url.indexOf(Object.values(params)[0]) + Object.values(params)[0].length) |
| 304 | |
| 305 | req.url = lead(url) |
| 306 | } else { |
| 307 | req.url = lead(req.url.substring(path.length)) |
| 308 | } |
| 309 | |
| 310 | req.path = getPathname(req.url) |
no test coverage detected