🚧 library is in alpha dev mode 🚧
Snow Splash
~1kB inversion of control container for Typescript/Javascript with a focus on async flow
- fully async: merges async and a constructor injection via an async functiom (asynchronous factory pattern)
- clean: does not mix application logic with framework
extends
, library @decorators
or other magic properties - lazy: initializes your app modules, packed into containers on demand
- split-chunks: core is fully async and it provides a way to split application logic into chunks
- typesafe: works well with typescript
- react: has useful react bindings to help separate application logic and react view layer
- lightweight: doesn't rely on 'reflect-metadata' or decorators
- tiny: ~1kB
Snow-Splash relies on containers to provide usefull grouping. Containers group a couple of initialized instances together. Containers form a DAG (directed acyclic graph) and containers (nodes) are initialized on request and dependency tree is initialized automatically. This might resemble DI mechanisms
Usage
npm install -S snow-splash`
import { RootContainer } from "snow-splash"
import { Oven, Kitchen, OrderManager } from "./kitchen/"
import { PizzaPlace, DiningTables } from "./pizza-place/"
export async function provideKitchenContainer() {
const oven = new Oven()
await oven.preheat()
return {
oven: oven,
kitchen: new Kitchen(oven),
orderManager: new OrderManager(kitchen),
}
}
export async function providePizzaPlaceContainer(kitchenContainer) {
return {
pizzaPlace: new PizzaPlace(kitchenContainer.kitchen),
diningTables: new DiningTables(),
}
}
export function getProviders(ctx) {
return {
kitchen: async () => provideKitchenContainer(),
pizzaContainer: async () => providePizzaPlaceContainer(await ctx.kitchen()),
}
}
export function getMainPizzaAppContainer() {
return new RootContainer(getProviders)
}
import { getMainPizzaAppContainer } from "./app"
const pizzaApp = getMainPizzaAppContainer()
const { pizzaContainer, kitchen } = await pizzaApp.containers
pizzaContainer.orders.orderPizza()
console.log(`In Oven: ${kitchen.oven.pizzasInOven()}`)
export const PizzaData = () => {
const kitchenContainerSet = useContainerSet((c) => [
c.kitchen,
c.pizzaContainer,
])
if (!kitchenContainerSet) return <>Kitchen is loading </>
const { pizzaContainer, kitchen } = kitchenContainerSet
return (
<div>
Pizzaz in Oven: {kitchen.oven.pizzasInOven()}
<button onClick={() => pizzaContainer.orders.orderPizza()}>
Order pizza
</button>
</div>
)
}
Motivation
Inversion of Control (IoC) is a great way to decouple the application and the most popular pattern of IoC is dependency injection (DI) but it is not limited to one.
In JavaScript there is not way to create a dependency injection without mixing application logic with a specific IoC library code, or hacking a compiler.
snow-splash
provides a pattern to use constructor injection that works in async JS world with all the flexibility you might need at the cost of manually defining providers (async functions) for your code
Why another library? Alternatives
Javascript does not provide advanced OO primitives unlike Java or C#. Libraries like InversifyJS or tsyringe rely on decorators and reflect-metadata
to enable DI.
This has a major downside as it "mixes" your application logic code with framework decorator imports or magic variables. This is can also be a downside since it provides a lock-in.
If two teams in your organization pick two different IoC/DI libs, it would be hard to share code.
inversifyjs
and tsyringe
use decorators and reflect-metada
import { injectable } from "tsyringe"
@injectable()
class Foo {
constructor(private database: Database) {}
}
import "reflect-metadata"
import { container } from "tsyringe"
import { Foo } from "./foo"
const instance = container.resolve(Foo)
typed-inject
uses magic properties and monkey-patching
import { createInjector } from "typed-inject"
function barFactory(foo: number) {
return foo + 1
}
barFactory.inject = ["foo"] as const
class Baz {
constructor(bar: number) {
console.log(`bar is: ${bar}`)
}
static inject = ["bar"] as const
}
With Snow-Splash your application logic is not mixed with the framework code
import type { Ingredients } from "./store.ingrediets"
import type { Oven } from "./store.oven"
export class Kitchen {
constructor(private oven: Oven, private ingredients: Ingredients) {}
}
import { IngredientsService } from "../services/ingredients-manager"
import { Kitchen } from "../stores/store.kitchen"
import { Oven } from "../stores/store.oven"
export async function provideKitchenContainer() {
let oven = new Oven()
let ingredients = await IngredientsService.buySomeIngredients()
let kitchen = new Kitchen(oven, ingredients)
return {
oven: oven,
ingredients: ingredients,
kitchen: kitchen,
}
}
Notable inspirations:
Getting Started
The best way to get started is to check a Pizza example
Initial wiring
import { makeRoot, RootContainer } from "../../library.root-container"
import { provideAContainer } from "./container.a"
import { provideBContainer } from "./container.b"
import { provideCContainer } from "./container.c"
interface Registry {
aCont: () => ReturnType<typeof provideAContainer>
bCont: () => ReturnType<typeof provideBContainer>
cCont: () => ReturnType<typeof provideCContainer>
}
type Lib = (...args: any) => { [K in keyof Registry]: Registry[K] }
export type MockAppContainer = RootContainer<Lib, ReturnType<Lib>>
function getProviders(ctx: Registry, root: MockAppContainer) {
return {
aCont: async () => provideAContainer(),
bCont: async () => provideBContainer(await ctx.aCont()),
cCont: async () =>
provideCContainer(await ctx.aCont(), await ctx.bCont(), root),
}
}
export function getMainMockAppContainer() {
return makeRoot(getProviders)
}
Typescript
Snow-Splash has a good typescript support
Docs
Tokens
Containers
Containers are an important unit.
If you replace them, users will be notified. In react it happens automatically
API documentation JS / TS
makeRoot
Setting app root
import { makeRoot, RootContainer } from "../../library.root-container"
export function getMainMockAppContainer() {
return makeRoot(getProviders)
}
containers
getter
let appRoot = getMainPizzaAppContainer()
let kitchen = await appRoot.containers.kitchen
kitchen.oven.pizzaCapacity
getContainerSet
getContainerSetNew
replaceCointerInstantly
When containers are updated react is updated too via hooks
replaceCointerAsync
API documentation React
getContainerSetHooks
Generates a set of app specific container hooks
import React, { useContext } from "react"
import { getContainerSetHooks } from "snow-splash"
import { getProviders, PizzaAppContainer } from "./_root.store"
export const MyRootCont = React.createContext(<PizzaAppContainer>{})
let mega = getContainerSetHooks(getProviders, MyRootCont)
export const useContainerSet = mega.useContainerSet
export const useContainerSetNew = mega.useContainerSetNew
import { useContainerSet } from "./my-app-hooks"
export const PizzaData = () => {
const containerSet = useContainerSetNew((containers) => [containers.kitchen])
console.log(containerSet)
return 123
}
useContainer
export const PizzaData = () => {
const [kitchenContainer, err] = useContainer().kitchen
if (!kitchenContainer || err) {
return <>Kitchen is loading</>
}
return <>{kitchenContainer.oven.pizzasInOven}</>
}
useContainerSet
Get multiple containers and autosubscribes to change.
export const PizzaData = () => {
const containerSet = useContainerSetNew((containers) => [
containers.kitchen,
containers.auth,
])
if (!containerSet) {
return <>Kitchen is loading</>
}
return <>{containerSet.kitchen.oven.pizzasInOven}</>
}
generateEnsureContainerSet
You can create a simpler API for a portion of your applicatoin to avoid dealing with async in every component. There are some helpfull Context helpers at your service. Also you can use classic props drilling to avoid dealing with async flow in every component
import React, { useContext } from "react"
import { useContainerSet } from "../containers/_container.hooks"
import { generateEnsureContainerSet } from "snow-splash"
const x = generateEnsureContainerSet(() =>
useContainerSet(["kitchen", "pizzaContainer", "auth"]),
)
export const EnsureNewKitchenConainer = x.EnsureWrapper
export const useNewKitchenContext = x.contextHook
export const PizzaApp = () => {
return (
<div>
Pizza App:
<EnsureNewKitchenConainer
fallback={<>Pizza App is still loading please wait</>}
>
<NewPizzaPlaceControls />
</EnsureNewKitchenConainer>
</div>
)
}
export const PizzaData = () => {
const { kitchen, pizzaContainer } = useNewKitchenContext()
return (
<div>
<div>Name: {kitchen.kitchen.kitchenName}</div>
<div>Tables: {pizzaContainer.diningTables.tables}</div>
</div>
)
}
Questions and tips
Can I have multiple application containers?
Yes, no problem at all. If you want, they can even share tokens and hence instances!