From 35c51e5ad51b6eb70f9da49feab2da759db23f5c Mon Sep 17 00:00:00 2001 From: Nikita Zavadin Date: Fri, 20 Sep 2024 13:36:27 +0200 Subject: [PATCH] Update README.md --- README.md | 33 +++++++++++++++++++++++++++++++++ src/magic_di/healthcheck.py | 3 ++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 04d83aa..45f200e 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Dependency Injector with minimal boilerplate code, built-in support for FastAPI * [Custom integrations](#custom-integrations) * [Manual injection](#manual-injection) * [Forced injections](#forced-injections) +* [Healthcheck](#healthcheck) * [Testing](#testing) * [Default simple mock](#default-simple-mock) * [Custom mocks](#custom-mocks) @@ -330,6 +331,38 @@ class Service(Connectable): dependency: Annotated[NonConnectableDependency, Injectable] ``` +## Healthchecks +You can implement `Pingable` protocol to define healthchecks for your clients. The `DependenciesHealthcheck` will call the `__ping__` method on all injected clients that implement this protocol. + +```python +from magic_di.healthcheck import DependenciesHealthcheck + + +class Service(Connectable): + def __init__(self, db: Database): + self.db = db + + def is_connected(self): + return self.db.connected + + async def __ping__(self) -> None: + if not self.is_connected(): + raise Exception("Service is not connected") + + +@app.get(path="/hello-world") +def hello_world(service: Provide[Service]) -> dict: + return { + "is_connected": service.is_connected() + } + + +@app.get(path="/healthcheck") +async def hello_world(healthcheck: Provide[DependenciesHealthcheck]) -> dict: + await healthcheck.ping_dependencies() + return {"alive": True} +``` + ## Testing If you need to mock a dependency in tests, you can easily do so by using the `injector.override` context manager and still use this dependency injector. diff --git a/src/magic_di/healthcheck.py b/src/magic_di/healthcheck.py index 8dff918..3004e14 100644 --- a/src/magic_di/healthcheck.py +++ b/src/magic_di/healthcheck.py @@ -13,7 +13,8 @@ async def __ping__(self) -> None: ... @dataclass class DependenciesHealthcheck(Connectable): """ - Injectable Healthcheck component that pings all dependencies that implement the PingableProtocol + Injectable Healthcheck component that pings all injected dependencies + that implement the PingableProtocol Example usage: