Skip to content

Koa

Quick guide to integrate Vla with Koa.

View Example App

Terminal window
npm install vla

Create src/data/kernel.ts:

import { Kernel } from 'vla'
export const kernel = new Kernel()

Add Vla middleware to your Koa app:

import Koa from 'koa'
import Router from '@koa/router'
import { Vla } from 'vla'
import { kernel } from './data/kernel'
const app = new Koa()
const router = new Router()
// Add Vla middleware
app.use(async (ctx, next) => {
await Vla.withKernel(kernel.scoped(), next)
})
// Your routes...
router.get('/users/:id', async (ctx) => {
const user = await GetUser.invoke(ctx.params.id)
ctx.body = user
})
app.use(router.routes())
app.listen(3000)

This creates a scoped kernel for each request.

src/data/users.actions.ts
import { Vla } from 'vla'
class GetUser extends Vla.Action {
async handle(id: string) {
// Your logic here
return { id, name: 'User' }
}
}
// src/server.ts
router.get('/users/:id', async (ctx) => {
const user = await GetUser.invoke(ctx.params.id)
ctx.body = user
})

To access the Koa context object, create a context:

src/data/context.ts
import { Vla } from 'vla'
import type { Context } from 'koa'
export const AppContext = Vla.createContext<{
ctx: Context
}>()

Update your middleware:

import { Vla } from 'vla'
import { kernel } from './data/kernel'
import { AppContext } from './data/context'
app.use(async (ctx, next) => {
await Vla.withKernel(
kernel.scoped().context(AppContext, { ctx }),
next
)
})

Use in your classes:

class GetCurrentUser extends Vla.Action {
ctx = this.inject(AppContext)
async handle() {
const sessionId = this.ctx.ctx.cookies.get('session_id')
// Use context data
}
}

You’re ready to use Vla in your Koa app. Check out the guides to learn how to structure your code with Actions, Services, and Repos.