Skip to content

Express

Quick guide to integrate Vla with Express.

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 Express app:

import express from 'express'
import { Vla } from 'vla'
import { kernel } from './data/kernel'
const app = express()
// Add Vla middleware
app.use((req, res, next) => {
Vla.withKernel(kernel.scoped(), next)
})
// Your routes...
app.get('/users/:id', async (req, res) => {
const user = await GetUser.invoke(req.params.id)
res.json(user)
})
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
app.get('/users/:id', async (req, res) => {
const user = await GetUser.invoke(req.params.id)
res.json(user)
})

To access the Express request and response objects, create a context:

src/data/context.ts
import { Vla } from 'vla'
import type { Request, Response } from 'express'
export const AppContext = Vla.createContext<{
req: Request
res: Response
}>()

Update your middleware:

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

Use in your classes:

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

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