Skip to content

Commit

Permalink
feat: can resolve another dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
maou-shonen committed Oct 26, 2024
1 parent e55e50c commit 48be7f6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,16 @@ userServiceDep.injection({

---

### Reference another dependency

```ts
const postServiceDep = new Dependency(
async (c) => new PostService(await userServiceDep.resolve(c)),
);
```

---

### A service can also be something other than a class

For example, using headers from `c.req.headers`.
Expand Down
23 changes: 19 additions & 4 deletions src/dependency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ export class Dependency<Service> {
},
) {}

// service cache
private service?: Service;
// used as a basis for caching when evaluating the request scope
private lastRequest?: Request;

/**
* Injects a service instance directly. Useful for overriding the default service.
Expand All @@ -39,6 +42,21 @@ export class Dependency<Service> {
return this;
}

/**
* Resolve service.
*/
async resolve(c: Context): Promise<Service> {
// evaluate and clear the cache when handling the request scope
if (this.opts?.scope === "request" && this.lastRequest !== c.req.raw) {
this.service = undefined;
this.lastRequest = c.req.raw;
}

const service = (this.service ??= await this.serviceInitializer(c));

return service;
}

/**
* Creates a middleware that injects the service into the context.
*/
Expand All @@ -51,10 +69,7 @@ export class Dependency<Service> {
};
}> {
return async (c, next) => {
const service =
this.opts?.scope === "request"
? await this.serviceInitializer(c)
: (this.service ??= await this.serviceInitializer(c));
const service = await this.resolve(c);

c.set(contextKey, service);

Expand Down

0 comments on commit 48be7f6

Please sign in to comment.