@ldlework/categoric-containers
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

Categoric Containers

Decorate things. Bind them at runtime.

This is a simple library that lets you create your own decorators. You can use these decorators to tag classes such that you can easily bind them all to a specific Inversify container.

Example

In this example, we have two categories of types, enemy related and item related.

We'll define two of each, and show how we can bind them independently from each other.

Enemies

// decorators/enemy.ts
import { createCategoricContainer } from "categoric-decorators"

export const { 
    install: installEnemies,
    singleton: enemy,
} = createClassCategoric()
// enemies/IEnemy.ts
export abstract class IEnemy { 
    // ...
}
// enemies/SnakeEnemy.ts
@enemy(IEnemy)
export class SnakeEnemy implements IEnemy {
    // ...
}
// enemies/SpiderEnemy.ts
@enemy(IEnemy)
class SpiderEnemy implements IEnemy {
    // ...
}

Items

// decorators/item.ts
import { createCategoricContainer } from "categoric-decorators"

export const { 
    install: installItems,
    singleton: enemy,
} = createClassCategoric()
// enemies/IItem.ts
export abstract class IItem { 
    // ...
}
// enemies/SwordItem.ts
@item(IItem)
export class SwordItem implements IItem {
    // ...
}
// enemies/PotionItem.ts
@item(IItem)
class PotionItem implements IItem {
    // ...
}

Binding

Now if we need to, we can bind these two groups of classes independently:

const enemyContainer = new Container()
installEnemies(enemyContainer)
const enemies = enemyContainer.getAll<IEnemy>()

const itemContainer = new Container()
installItems(itemContainer)
const items = itemContainer.getAll<IItem>()

Installation

npm i @ldlework/categoric-containers

Creating Categories

To create a category, use createCategoricContainer():

export const { install, makeChild, singleton, transient, request } = createClassCategoric()

This creates a number of functions and decorators:

  • install(container: Container) - binds all classes in the category to the container
  • makeChild(container: Container) - creates a child container and binds all classes in the category to it
  • singleton(target?: interfaces.ServiceIdentifier) - decorator for singleton classes
  • transient(target?: interfaces.ServiceIdentifier) - decorator for transient classes
  • request(target?: interfaces.ServiceIdentifier) - decorator for request classes

Read more about inversify scopes here.

Readme

Keywords

none

Package Sidebar

Install

npm i @ldlework/categoric-containers

Weekly Downloads

0

Version

0.0.2

License

ISC

Unpacked Size

26.6 kB

Total Files

13

Last publish

Collaborators

  • ldlework