Replies: 1 comment
-
|
Your second approach (the A few clarifications on why the decorator fights the framework. Litestar's handler resolution uses signature-based DI. When you wrap the handler in a decorator that does On guards, they run before dependency resolution, not after, so they have the connection scope but not the resolved services. That makes them right for cheap checks (does the request have a header? is this under So the dependency you wrote is the cleanest expression of "this check runs after services are resolved, before the handler body": async def assert_user_can_see_part(
part_number: str,
part_service: PartService,
) -> str:
await part_service.can_user_see_part(part_number)
return part_number
@get(
path="/{part_number:str}/bom",
dependencies={"part_number": Provide(assert_user_can_see_part)},
)
async def get_part_bom(
part_number: str,
part_service: PartService,
) -> list[PartBomComponent]:
return await part_service.get_part_bom(part_number=part_number)Small naming tweak. Name it as an assertion ( For broader reuse across many routes, lift the dependency to the controller or router level instead of repeating it on each handler. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have a route that essentially returns a single level BOM for a part. I want to validate that the user requesting the data has access to the top level part and that requires me to call a service function. Originally, I had the two service calls in the router function to validate that the user can see the part, then get the BOM data. I wanted to abstract it out so I can use the same logic on other parts. My first thought was to use a decorator:
This will throw an error if the user cannot see the part, and will not execute the function.
In my controller, the function its being used in looks like this:
My concern with this approach is that it might be an anti-pattern in the litestar framework. I have been trying to look at other approaches like a guard or the before request, but my understanding, which may be wrong, is the dependency resolution occurs after the guard and before requested are executed. Since the Service is resolved via the dependency injector, I have to execute the check after that occurs. Does anyone have any ideas on if there are other ways to achieve this? Is this the best approach? The only other way that I can think of is by using the dependencies and have it look like this:
Any insights or thoughts on this would be greatly appreciated.
Beta Was this translation helpful? Give feedback.
All reactions