Skip to content

Commit

Permalink
refactor(proxy): integrate custom mapping process to enhance response…
Browse files Browse the repository at this point in the history
… content handling
  • Loading branch information
yufeikang committed May 26, 2024
1 parent 0bd3f70 commit c9440ce
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
8 changes: 7 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@
from fastapi.responses import StreamingResponse
from google.generativeai import GenerativeModel

from app.utils import ProxyRequest, pass_through_request, json_dumps
from app.utils import (
ProxyRequest,
pass_through_request,
json_dumps,
process_custom_mapping,
)

logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"))

Expand Down Expand Up @@ -552,6 +557,7 @@ async def proxy(request: Request):
data["admin"] = True
add_user(request, data["email"])
content = json_dumps(data, ensure_ascii=False).encode("utf-8")
content = process_custom_mapping(content, req)
return Response(
status_code=response.status_code,
content=content,
Expand Down
20 changes: 13 additions & 7 deletions app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,19 @@ async def pass_through_request(client: httpx.AsyncClient, request: ProxyRequest)
if key not in filtered_headers
}
# check and modify response content
if MAPPING_CONFIG and content:
content = process_custom_mapping(content, request)
return ProxyResponse(
status_code=response.status_code, content=content, headers=response_headers
)


def process_custom_mapping(content: bytes, request: ProxyRequest):
if not content:
return content
if MAPPING_CONFIG:
try:
json_content = json.loads(content)
path = url.removeprefix(RAYCAST_BACKEND)
path = request.url.removeprefix(RAYCAST_BACKEND)
key = _get_mapping_key(path, request.method, "response:body")
if key in MAPPING_CONFIG:
for json_path_expr, value in MAPPING_CONFIG[key].items():
Expand All @@ -155,14 +164,11 @@ async def pass_through_request(client: httpx.AsyncClient, request: ProxyRequest)
for match_obj in match:
logger.debug(f"Matched json path: {match_obj.value}")
match_obj.context.value[match_obj.path.fields[-1]] = value
content = json.dumps(json_content, ensure_ascii=False).encode("utf-8")
return json.dumps(json_content, ensure_ascii=False).encode("utf-8")
except Exception as e:
logger.error("Error occurred while modifying response content")
logger.error(e)

return ProxyResponse(
status_code=response.status_code, content=content, headers=response_headers
)
return content


def json_dumps(*args, **kwargs):
Expand Down

0 comments on commit c9440ce

Please sign in to comment.