Skip to content

Commit

Permalink
feat(inversify-code-examples): add bindingWhenSyntaxApiWhen example
Browse files Browse the repository at this point in the history
  • Loading branch information
notaphplover committed Jan 16, 2025
1 parent 105fdd1 commit 2476337
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { describe, expect, it } from '@jest/globals';

import { ninjaDamage } from './bindingWhenSyntaxApiWhen';

describe('BindingWhenSyntax API (when)', () => {
it('should bind right ninja weapon', () => {
expect(ninjaDamage).toBe(5);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {
BindingMetadata,
Container,
inject,
injectable,
named,
} from 'inversify7';

interface Weapon {
damage: number;
}

export class Katana implements Weapon {
public readonly damage: number = 10;
}

export class Shuriken implements Weapon {
public readonly damage: number = 5;
}

const container: Container = new Container();

// Begin-example
const ninjaId: symbol = Symbol.for('Ninja');
const weaponId: symbol = Symbol.for('Weapon');

@injectable()
class Ninja {
constructor(
@inject(weaponId)
@named('shuriken')
public readonly weapon: Weapon,
) {}
}

container.bind<Ninja>(ninjaId).to(Ninja);

const whenTargetNamedConstraint: (
name: string,
) => (bindingMetadata: BindingMetadata) => boolean =
(name: string) =>
(bindingMetadata: BindingMetadata): boolean =>
bindingMetadata.name === name;

container
.bind<Weapon>(weaponId)
.to(Katana)
.when(whenTargetNamedConstraint('katana'));

container
.bind<Weapon>(weaponId)
.to(Shuriken)
.when(whenTargetNamedConstraint('shuriken'));

const ninja: Ninja = container.get(ninjaId);

// Returns 5
const ninjaDamage: number = ninja.weapon.damage;
// End-example

export { ninjaDamage };

0 comments on commit 2476337

Please sign in to comment.