Koa
Quick guide to integrate Vla with Koa.
View Example App
Install
Section titled “Install”npm install vlaCreate Kernel
Section titled “Create Kernel”Create src/data/kernel.ts:
import { Kernel } from 'vla'
export const kernel = new Kernel()Set Up Middleware
Section titled “Set Up Middleware”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 middlewareapp.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.
Use in Routes
Section titled “Use in Routes”import { Vla } from 'vla'
class GetUser extends Vla.Action { async handle(id: string) { // Your logic here return { id, name: 'User' } }}
// src/server.tsrouter.get('/users/:id', async (ctx) => { const user = await GetUser.invoke(ctx.params.id) ctx.body = user})Access Koa Context (Optional)
Section titled “Access Koa Context (Optional)”To access the Koa context object, create a context:
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 }}That’s It
Section titled “That’s It”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.