Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

koa-depsi

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

koa-depsi

Dependencies injection middleware for Koa

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

Koa-depsi

This package allow you to easily inject dependencies in your koa app. In the example below we inject a database connection. This allow us to call the database from our handlers by using the ctx.deps.db object.

Of course injecting dependencies is usefull in testing context. This middleware will allow you to inject a fake db client through your Koa application to avoid calling a real database in your routes.

/app.js

const Koa = require('koa')
const koadepsi = require('koa-depsi')

function createApp(dependencies = {}) {
  const app = new Koa()

  /**
   * This will expose the object dependencies on the koa context : ctx.deps
   */
  app.use(koadepsi(dependencies))

  /**
   * If you use koa-router you can inject dependencies on specific routes only
   */
  const Router = require('koa-router');
  const router = new Router();
  router.use('/products', koadepsi(dependencies.productsController))

  return app
}

module.exports = createApp

/index.js

const database = require('whatever-db-you-want')
const app = require('./app')

const dependencies = { db: database }

app(dependencies).listen()

/routes/users/getById.js

async function getUserById(ctx) {
  /**
   * Here you can retrieve your database connection from the Koa context
   */
  const db = ctx.deps.db
  const user = await db.user.getById(ctx.params.id)
  ctx.status = 200
  ctx.body = { user }
}

module.exports = getUserById

Keywords

koa

FAQs

Package last updated on 31 Mar 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts