Skip to content

Commit 41e65b2

Browse files
committed
added router prefix support and fixed bug with named paramters not being handled
1 parent 4432604 commit 41e65b2

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

src/services/languages/python/fastapiEndpointExtractor.ts

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,32 @@ export class FastapiEndpointExtractor implements IEndpointExtractor
1111
// Ensure fastapi module was imported
1212
if(!tokens.any(t => t.text == 'fastapi' && t.type == TokenType.module))
1313
return [];
14+
15+
let prefix = '';
1416

1517
// Search for "@app.get" decorators
16-
const results: EndpointInfo[] = []
18+
const results: EndpointInfo[] = [];
1719
for(let i=0; i<tokens.length-1; i++)
1820
{
1921
const appToken = tokens[i];
2022
const methodToken = tokens[i+1];
23+
24+
//Check if this is a router variable
25+
if ( appToken.type === TokenType.variable
26+
&& methodToken.type === TokenType.class && methodToken.text==='APIRouter' ){
27+
28+
const routerLine = document.getText(new vscode.Range(
29+
appToken.range.start,
30+
new vscode.Position(methodToken.range.end.line, 1000)));
31+
32+
//extract the prefix
33+
let match = new RegExp(`^${appToken.text}\\s*=\\s*\\APIRouter\\s*\\((.*=.*,\\s*)*prefix=\\s*["'](.*?)["'](ֿֿֿ\\s*,.*=.*)*\\)*\\)`).exec(routerLine);
34+
if (match){
35+
prefix = match[2];
36+
}
37+
}
38+
39+
2140
if ((appToken.text != 'app' && appToken.text != 'router') || appToken.type != TokenType.variable || methodToken.type != TokenType.method)
2241
continue;
2342

@@ -28,17 +47,25 @@ export class FastapiEndpointExtractor implements IEndpointExtractor
2847
const lineText = document.getText(new vscode.Range(
2948
appToken.range.start,
3049
new vscode.Position(methodToken.range.end.line, 1000)));
31-
const match = new RegExp(`^(app|router)\\.${method}\\(["'](.*?)["']`).exec(lineText);
50+
51+
let index = 2;
52+
let match = new RegExp(`^(app|router)\\.${method}\\(["'](\/.*?)["']`).exec(lineText);
53+
if (!match){
54+
//Different regex for optional params (named)
55+
match = new RegExp(`^(app|router)\\.${method}\\((.*=.*,\\s*)*path=\\s*["'](\\/.*?)["'](ֿֿֿ\\s*,.*=.*)*\\)`).exec(lineText);
56+
index =3;
57+
}
58+
3259
if (!match)
3360
continue;
3461

3562
const relevantFunc = symbolInfo.firstOrDefault(s => s.range.contains(methodToken.range))
3663
if (!relevantFunc)
3764
continue;
3865

39-
const path = match[2];
66+
const path = match[index];
4067
results.push(new EndpointInfo(
41-
vscode.workspace.getWorkspaceFolder(document.uri)!.name + '$_$' + method + ' ' + path,
68+
vscode.workspace.getWorkspaceFolder(document.uri)!.name + '$_$' + method + ' ' + prefix + path,
4269
method,
4370
path,
4471
relevantFunc.range,

0 commit comments

Comments
 (0)