npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

disclosure-di

v0.1.0

Published

A typesafe based DI container

Downloads

2

Readme

Disclosure

Minimalistic typesafe IOC container written in strict-mode typescript

Installation

Usage

Binding values

import { ChainingContainer } from 'disclosure-di'

// create container, matching FinalConfig will be type checked
const container = new ChainingContainer()
    // binding exact values
    .bind('num').toValue(10)
    .bind('str').toValue('ok')
    .bind('arr').toValue([10, 20])
    .bind('fun').toValue(console.log)
    .bind('obj').toValue({
        a: 'a',
        b: [15, 25]
    })

container.get('num') // 10
container.get('arr') // [10, 20]

Binding factories

The heart of this lib

import { ChainingContainer, Container, DITools } from 'disclosure-di'

// we will check container type against this one
interface FinalConfig {
    num: number
    str: string
    arr: number[]
    fun: (arg: any) => void
    obj: {
        a: string,
        b: number[]
    }
}

// Create makeFactory with predefined config
const di = new DITools<FinalConfig>().makeFactory

// di(...identifiers, (...identifierValues) => Instance))
const numNSquare = di('num', (base) => [base, base * base])

// There are no limitations on returned type
const log = di('str', (prefix) => (x: any) => console.log(prefix, x))

// You can depend on up to 20 identifiers
const obj = di('str', 'arr', (str, arr) => ({
    a: str,
    b: arr
}))

// You will get a typescript error if any identifier is missing / has incorrect type
const container: Container<FinalConfig> = new ChainingContainer()
    // binding exact values
    .bind('num').toValue(10)
    .bind('str').toValue('ok')
    .bind('arr').toFactory(numNSquare)
    .bind('fun').toFactory(log)
    .bind('obj').toFactory(obj)

container.get('num') // 10
container.get('arr') // [10, 100]
container.get('obj') // { a: 'ok', b: [10, 100] }


// --CAVEAT--
// Even though this api uses chaining you won't get the right type if you do this
const container = new ChainingContainer()

container
    .bind('num').toValue(10)
    .bind('str').toValue('ok')
    .bind('arr').toFactory(numNSquare)
    .bind('fun').toFactory(log)
    .bind('obj').toFactory(obj) 
    
container // sadly, container is still Container<{}>

Binding classes

Boils down to factories

import { ChainingContainer, Container, DITools, toClass } from 'disclosure-di'

class Genius {
    constructor(
        public answer: number,
        private connector: string
    ) { } // values are assigned automatically

    public explain(question: string) {
        console.log(question, this.connector, this.answer)
    }
}

// we will check container type against this one
interface FinalConfig {
    num: number
    connector: string
    genius: Genius
    sugar: Genius
    create: (answer: number) => Genius
}

const di = new DITools<FinalConfig>().makeFactory

const container: Container<FinalConfig> = new ChainingContainer()
    .bind('num').toValue(42)
    .bind('connector').toValue('is an alias to')
    .bind('genius').toFactory(di('num', 'connector', (ans, connector) => new Genius(ans, connector)))
    .bind('sugar').toFactory(di('num', 'connector', toClass(Genius)))
    .bind('create').toFactory(di('connector', (connector) => (ans: number) => new Genius(ans, connector)))

container.get('genius').explain('Universe') // Universe is an alias to 42

// code equal to binding to constructor
const create = container.get('create')
create(Infinity).explain('Your skill') // Your skill is an alias to Infinity

toClass helper just converts class construction to factory

This approach is used because using classes (in our experience) makes refactoring code to plain values really hard, while classes tend to get fat, while method overriding makes code harder to reason about.

Also this approach gives you more control in terms of splitting values into received from container and received from usage without unclear limitations like being unable to use values from DI container in the constructor

Binding as singletons

Useful for shared objects, event buses and any other integration

// tslint:disable:no-console
import { ChainingContainer, Container, DITools } from 'disclosure-di'

type Subscriber = () => any

interface FinalConfig {
    tickInterval: number
    tick: (cb: Subscriber) => void
}

const di = new DITools<FinalConfig>().makeFactory

const tick = di('tickInterval', (time) => {
    const subs = [] as Subscriber[]
    setInterval(() => subs.forEach((sub) => sub()), time)

    return (cb: Subscriber) => subs.push(cb)
})

const container: Container<FinalConfig> = new ChainingContainer()
    .bind('tickInterval').toValue(1000)
    .bind('tick').toFactory(tick).asSingleton() // we want everything to trigger together

container.get('tick')(() => console.log('logic'))

setTimeout(() => {
    // it's pretty safe to use container as service locator if you bind everything in the beginning
    container.get('tick')(() => console.log('render\n\n'))
}, 600)

// logic
// render // instantly, instead of 600ms late

Binding as extensions

Useful for all sorts of plugins / extensions

🛠 TBD 🛠

Use container.bindMore for a key that has an array bound to it

import { ChainingContainer, Container, DITools } from 'disclosure-di'

// we will check container type against this one
interface FinalConfig {
    spearLength: number,
    weapons: string[]
}

// Create makeFactory with predefined config
const di = new DITools<FinalConfig>().makeFactory
const spearFactory = di('spearLength', (len) => len > 3 ? 'long spear' : 'short spear')
// You will get a typescript error if any identifier is missing / has incorrect type
const container: Container<FinalConfig> = new ChainingContainer()
    // binding exact values
    .bind('weapons').toValue(['sword', 'bow'])
    .bindMore('weapons').toValue('knife')
    .bindMore('weapons').toFactory(spearFactory)
    .bind('spearLength').toValue(2.4)
// you can still use singleton bindings with bindMore, even though they are missing in this example

console.log(
    container.get('weapons') // [ 'sword', 'bow', 'knife', 'short spear' ]
)

Cookbook

🛠 TBD 🛠

Composing container of modules

Using disclosure for A / B tests