@@ -27,7 +27,6 @@ class TenantLinksMiddleware(JsonResponseMiddleware):
2727 """
2828
2929 app : FastAPI
30- root_path : str = ""
3130 json_content_type_expr : str = r"application/(geo\+)?json"
3231
3332 def should_transform_response (self , request : Request , scope : Scope ) -> bool :
@@ -47,34 +46,31 @@ def transform_json(self, data: dict[str, Any], request: Request) -> dict[str, An
4746 """Update links in the response to include root_path."""
4847 # Get the client's actual base URL (accounting for load balancers/proxies)
4948 tenant = request .state .tenant
50- origin = f"{ request .url .scheme } ://{ request .url .netloc } "
49+ root_path = request .scope .get ("root_path" , "" )
50+ base_url = f"{ request .url .scheme } ://{ request .url .netloc } { root_path } "
5151 for link in get_links (data ):
5252 # Ignore links that aren't for this application (e.g. other origin or prefix)
53- if not link .get ("href" , "" ).startswith (origin ):
53+ if not link .get ("href" , "" ).startswith (base_url ):
5454 logger .debug (
5555 "Ignoring link %r because it doesn't start with %r" ,
5656 link .get ("href" ),
57- origin ,
57+ base_url ,
5858 )
5959 continue
6060 try :
61- self ._update_link (link , tenant )
61+ url_parsed = urlparse (link ["href" ])
62+ # /api/stac/collections -> /collections
63+ path_without_root_path = url_parsed .path [len (root_path ) :]
64+ # /collections -> /api/stac/{tenant}/collections
65+ url_parsed = url_parsed ._replace (
66+ path = f"{ root_path } /{ tenant } { path_without_root_path } "
67+ )
68+ logger .debug ("Updated link %r to %r" , link ["href" ], urlunparse (url_parsed ))
69+ link ["href" ] = urlunparse (url_parsed )
6270 except Exception as e :
6371 logger .error (
6472 "Failed to parse link href %r, (ignoring): %s" ,
6573 link .get ("href" ),
6674 str (e ),
6775 )
6876 return data
69-
70- def _update_link (self , link : dict [str , Any ], tenant : str ) -> None :
71- """Update link to include tenant."""
72- url_parsed = urlparse (link ["href" ])
73- # /api/stac/collections -> /collections
74- path_without_root_path = url_parsed .path [len (self .root_path ) :]
75- # /collections -> /api/stac/{tenant}/collections
76- url_parsed = url_parsed ._replace (
77- path = f"{ self .root_path } /{ tenant } { path_without_root_path } "
78- )
79- logger .debug ("Updated link %r to %r" , link ["href" ], urlunparse (url_parsed ))
80- link ["href" ] = urlunparse (url_parsed )
0 commit comments