Skip to content
This repository was archived by the owner on May 14, 2025. It is now read-only.

Commit 8ef3dad

Browse files
committed
get matched route
1 parent 8a6a263 commit 8ef3dad

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

src/apitoolkit.ts

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { PubSub, Topic } from '@google-cloud/pubsub';
22
import { asyncLocalStorage, buildPayload, observeAxios, observeAxiosGlobal, ReportError } from 'apitoolkit-js';
33
import { AxiosInstance, AxiosStatic } from 'axios';
4-
import { NextFunction, Request, Response } from 'express';
4+
import { Application, NextFunction, Request, Response } from 'express';
55
import fetch from 'sync-fetch';
66
import { v4 as uuidv4 } from 'uuid';
77
export type ATError = {
@@ -255,7 +255,9 @@ export class APIToolkit {
255255
reqBody = String(req.body);
256256
}
257257
}
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 != '') {
259261
url_path = req.baseUrl + url_path;
260262
}
261263
const errors = asyncLocalStorage.getStore()?.get('AT_errors') ?? [];
@@ -305,10 +307,47 @@ export class APIToolkit {
305307
}
306308
});
307309
}
310+
308311
public errorHandler(err: any, req: Request, res: Response, next: NextFunction) {
309312
void ReportError(err);
310313
next(err);
311314
}
312315
}
313316

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+
314353
export default APIToolkit;

0 commit comments

Comments
 (0)