|
1 | 1 | import { PubSub, Topic } from '@google-cloud/pubsub';
|
2 | 2 | import { asyncLocalStorage, buildPayload, observeAxios, observeAxiosGlobal, ReportError } from 'apitoolkit-js';
|
3 | 3 | import { AxiosInstance, AxiosStatic } from 'axios';
|
4 |
| -import { NextFunction, Request, Response } from 'express'; |
| 4 | +import { Application, NextFunction, Request, Response } from 'express'; |
5 | 5 | import fetch from 'sync-fetch';
|
6 | 6 | import { v4 as uuidv4 } from 'uuid';
|
7 | 7 | export type ATError = {
|
@@ -255,7 +255,9 @@ export class APIToolkit {
|
255 | 255 | reqBody = String(req.body);
|
256 | 256 | }
|
257 | 257 | }
|
258 |
| - if (req.baseUrl && req.baseUrl != '') { |
| 258 | + if (url_path == '' && req.method.toLowerCase() !== 'head') { |
| 259 | + url_path = findMatchedRoute(req.app, req.method, req.originalUrl); |
| 260 | + } else if (req.baseUrl && req.baseUrl != '') { |
259 | 261 | url_path = req.baseUrl + url_path;
|
260 | 262 | }
|
261 | 263 | const errors = asyncLocalStorage.getStore()?.get('AT_errors') ?? [];
|
@@ -305,10 +307,47 @@ export class APIToolkit {
|
305 | 307 | }
|
306 | 308 | });
|
307 | 309 | }
|
| 310 | + |
308 | 311 | public errorHandler(err: any, req: Request, res: Response, next: NextFunction) {
|
309 | 312 | void ReportError(err);
|
310 | 313 | next(err);
|
311 | 314 | }
|
312 | 315 | }
|
313 | 316 |
|
| 317 | +export const findMatchedRoute = (app: Application, method: string, url: string): string => { |
| 318 | + try { |
| 319 | + let path = url.split('?')[0]; |
| 320 | + const stack = app._router.stack; |
| 321 | + let final_path = ''; |
| 322 | + |
| 323 | + const gatherRoutes = (stack: any, build_path: string, path: string) => { |
| 324 | + for (let layer of stack) { |
| 325 | + if (layer.route) { |
| 326 | + if (path.startsWith(layer.path)) { |
| 327 | + const route = layer.route; |
| 328 | + if (route.methods[method.toLowerCase()]) { |
| 329 | + const match = layer.path === path || layer.regex.test(path); |
| 330 | + if (match) { |
| 331 | + build_path += route.path; |
| 332 | + final_path = build_path; |
| 333 | + return; |
| 334 | + } |
| 335 | + } |
| 336 | + } |
| 337 | + } else if (layer.name === 'router' && layer.handle.stack) { |
| 338 | + if (path.startsWith(layer.path)) { |
| 339 | + build_path += layer.path; |
| 340 | + path = path.replace(layer.path, ''); |
| 341 | + gatherRoutes(layer.handle.stack, build_path, path); |
| 342 | + } |
| 343 | + } |
| 344 | + } |
| 345 | + }; |
| 346 | + gatherRoutes(stack, '', path); |
| 347 | + return final_path; |
| 348 | + } catch (error) { |
| 349 | + return ''; |
| 350 | + } |
| 351 | +}; |
| 352 | + |
314 | 353 | export default APIToolkit;
|
0 commit comments