molszanski / iti

~1kB Dependency Injection Library for Typescript and React with a unique support of async flow
https://itijs.org
MIT License
137 stars 7 forks source link

add disposing feature. `addDisposer` and `disposerAll` methods #26

Closed molszanski closed 2 years ago

molszanski commented 2 years ago

Related to a conversation with @moltar https://github.com/molszanski/iti/issues/21

Propblem

class DatabaseConnection {
  disconnect(): Promise<void> {
    // ... disconnect
  }
}

let node = makeRoot()
  .add({
    db: () => new DatabaseConnection(),
  })
  .dispose({
    db: (containers) => containers.db.disconnect(),
  })

// disposes of for all resources that have it defined
await node.dispose()

// under the hood (internals)
class Node {
  async dispose(): Promise<void> {
    await Promise.all(this.getDisposableResources().map((r) => r()))
  }
}