Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support async token factories #5

Merged
merged 1 commit into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/container.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe("Container API", () => {
.bind({
provide: otherToken,
async: true,
useFactory: () => new Promise<string>((resolve) => resolve("foo")),
useFactory: () => Promise.resolve("foo"),
})
.bind({
provide: token,
Expand Down
17 changes: 13 additions & 4 deletions src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,19 @@ export class Container {
superClass = Object.getPrototypeOf(superClass)
}
} else if (isInjectionToken(token) && token.options?.factory) {
this.bind({
provide: token,
useFactory: token.options.factory,
});
if (!token.options.async) {
this.bind({
provide: token,
async: false,
useFactory: token.options.factory,
});
} else if (token.options.async) {
this.bind({
provide: token,
async: true,
useFactory: token.options.factory,
});
}
}
}
}
Expand Down
5 changes: 1 addition & 4 deletions src/examples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,7 @@ describe("Container", () => {
.bind({
provide: tokenProvidedAsync,
async: true,
useFactory: () =>
new Promise<Foo>((resolve) => {
resolve({ foo: "async" });
}),
useFactory: () => Promise.resolve({ foo: "async" }),
});

expect(factoryFn).not.toHaveBeenCalled();
Expand Down
91 changes: 62 additions & 29 deletions src/providers.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { Container } from "./container.js";
import { InjectionToken } from "./tokens.js";
import { injectable } from './decorators.js';
import { injectable } from "./decorators.js";

const myServiceConstructorSpy = vi.fn();

class MyService {
constructor(public name = 'MyService') {
constructor(public name = "MyService") {
myServiceConstructorSpy();
}
}
Expand Down Expand Up @@ -106,7 +106,7 @@ describe("Providers", () => {
container.bind({
provide: MyService,
async: true,
useFactory: () => new Promise<MyService>(resolve => resolve(new MyService()))
useFactory: () => Promise.resolve(new MyService()),
});

expect(myServiceConstructorSpy).not.toHaveBeenCalled();
Expand All @@ -126,7 +126,7 @@ describe("Providers", () => {
expect(() => container.get(MyService)).toThrowError();
expect(container.get(MyService, { optional: true })).toBeUndefined();

const OTHER_TOKEN = new InjectionToken<MyService>('MyService');
const OTHER_TOKEN = new InjectionToken<MyService>("MyService");

container.bind(MyService);
container.bind({
Expand All @@ -144,16 +144,51 @@ describe("Providers", () => {
expect(myServiceConstructorSpy).toHaveBeenCalledTimes(1);
});

describe('abstract classes and inheritance', () => {
it("Token factories should be provided once", () => {
const container = new Container();

const TOKEN = new InjectionToken<MyService>("MyService", {
factory: () => new MyService(),
});

expect(myServiceConstructorSpy).not.toHaveBeenCalled();

const myService = container.get(TOKEN);

expect(myService).toBeInstanceOf(MyService);
expect(container.get(TOKEN)).toBe(myService);
expect(container.get(TOKEN, { optional: true })).toBe(myService);
expect(myServiceConstructorSpy).toHaveBeenCalledTimes(1);
});

it("Token async factories should be provided once", async () => {
const container = new Container();

const TOKEN = new InjectionToken<MyService>("MyService", {
async: true,
factory: () => Promise.resolve(new MyService()),
});

expect(myServiceConstructorSpy).not.toHaveBeenCalled();

const myService = await container.getAsync(TOKEN);

expect(myService).toBeInstanceOf(MyService);
expect(await container.getAsync(TOKEN)).toBe(myService);
expect(await container.getAsync(TOKEN, { optional: true })).toBe(myService);
expect(myServiceConstructorSpy).toHaveBeenCalledTimes(1);
});

describe("abstract classes and inheritance", () => {
abstract class AbstractService {
protected constructor(public name = 'AbstractService') {}
protected constructor(public name = "AbstractService") {}
}

it('should support annotated subclasses', () => {
it("should support annotated subclasses", () => {
@injectable()
class FooService extends AbstractService {
constructor(public fooProp = 'foo') {
super('FooService')
constructor(public fooProp = "foo") {
super("FooService");
}
}

Expand All @@ -165,34 +200,34 @@ describe("Providers", () => {
expect(container.get(AbstractService)).toBeInstanceOf(FooService);
});

it('should support binding subclasses', () => {
it("should support binding subclasses", () => {
class FooService extends AbstractService {
constructor(public fooProp = 'foo') {
super('FooService')
constructor(public fooProp = "foo") {
super("FooService");
}
}

class BarService extends AbstractService {
constructor(public fooProp = 'bar') {
super('BarService')
constructor(public fooProp = "bar") {
super("BarService");
}
}

const container = new Container();

container
.bind({
provide: FooService,
useClass: FooService
})
.bind({
provide: BarService,
useClass: BarService
})
.bind({
provide: AbstractService,
useExisting: FooService
})
.bind({
provide: FooService,
useClass: FooService,
})
.bind({
provide: BarService,
useClass: BarService,
})
.bind({
provide: AbstractService,
useExisting: FooService,
});

expect(container.get(FooService)).toBeInstanceOf(FooService);
expect(container.get(FooService)).toBeInstanceOf(AbstractService);
Expand All @@ -201,7 +236,5 @@ describe("Providers", () => {

expect(container.get(AbstractService)).toBeInstanceOf(FooService);
});


});
});
});
12 changes: 11 additions & 1 deletion src/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,20 @@ export type Token<T> =
| symbol
| InjectionToken<T>;

interface InjectionTokenOptions<T> {
async?: false,
factory: () => T
}

interface AsyncInjectionTokenOptions<T> {
async: true,
factory: () => Promise<T>
}

export class InjectionToken<T> {
constructor(
private description: string | symbol,
public options?: { factory: () => T },
public options?: InjectionTokenOptions<NoInfer<T>> | AsyncInjectionTokenOptions<NoInfer<T>>,
) {}

public toString(): string {
Expand Down
Loading