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

@occupop/lib-container

v1.2.2

Published

This package is intended to use as a Container for Dependency Injection... making Inversion of Control: Easy, Fast, Clean and Typesafe.

Downloads

312

Readme

Package @occupop/lib-container

This package is intended to use as a Container for Dependency Injection... making Inversion of Control: Easy, Fast, Clean and Typesafe.

This implementation wraps https://github.com/jeffijoe/awilix package! Check their docs for detailed/advanced usage.

NPM registry token required!

Install

# Yarn
yarn add @occupop/lib-container

# NPM
npm install @occupop/lib-container

# Bun
bun add @occupop/lib-container

Usage - Register

import { createTypedContainer } from '@occupop/lib-container'
//... all other imports omited... 

export const container = createTypedContainer({
    // Top-level
    graphqlServer: { asFunction: makeGraphqlServer, singleton: true },
    mongoClient: { asFunction: makeMongoClient, singleton: true },
    getMongoCollection: { asFunction: makeGetMongoCollection, singleton: true },
    // ... add .singleton() to top-level services to cache factory call 
    
    // Services
    fooService: { asFunction: makeFooService, scoped: true },
    barService: { asClass: BarService, scoped: true },
    // ... you can add .scoped() cache some lifecicle factory calls
    
    // Repositories
    fooRepository: { asFunction: makeFooRepository, singleton: true },
    barRepository: { asFunction: makeBarRepository, singleton: true },
    
    // Session scope (possible null)
    authUser: { asValue: null as AuthUser | null }, // for injecting AuthService.getUser()
    request: { asValue: null as Request | null }, // for injecting Express request
})

// typed dependencies to make inject easy...
type Deps = typeof container.cradle

Usage - Scoped register

In order to have a scoped container available in the request scope, we use to apply a context function to the server to intercept the request and create a scoped container createTypedContainerScope with request available and even the auth user ready to be used.

// context-function.ts
import { createTypedContainerScope } from '@occupop/lib-container'
//... all other imports omited... 

export function makeAuthContextFunction({ container, getAuthUser }: Deps) {
    return async (context) => {
        const authUser = await getAuthUser(context.req)
        const scopedContainer = createTypedContainerScope(container, {
            request: { asValue: context.req },
            authUser: { asValue: authUser },
        })
        return { ...context, container: scopedContainer }
    }
}

export type ScopedDeps = ReturnType<ReturnType<typeof makeAuthContextFunction>>['container']

NOTE: even having AuthUser available, NEVER require as a Service dependency! REMEMBER: all services should be able to be used from commands, queue, etc!

Usage - Creating Factories

// amazing-service.ts
import type { Deps } from '.container'

export function makeAmazingService({
   fooRepository,
   barRepository,
   randomDependencieHere,
    // ... dependencies will be type-hinted thanks to type Deps!
}: Deps) {
    return {
        foo: () => { /** ... nice and clean implementation ... */ },
        bar: () => { /** ... another clean implementation ... */ },
    }
}

Usage - Consuming

// server.ts
import { type Deps, container } from '.container'

container.build(async ({ logger, mongoClient, eventService }: Deps) => {
    await mongoClient.connect()
    logger.log('Mongo connected')
    eventService.consumer().start()
    logger.log('Worker ready!')
})

// OR ...

// server.ts
import { container } from '.container'

const { logger, mongoClient, eventService } = container.cradle
await mongoClient.connect()
logger.log('Mongo connected')
eventService.consumer().start()
logger.log('Worker ready!')

TODO

  • Improve later register to be made in the same format
  • Correct container self signature to inferred cradle type
  • Resolve circular reference from old version and keep awilix signature format