Skip to main content

CRUD Example

A complete CRUD (Create, Read, Update, Delete) example with Vegaa.

Code

import { vegaa, route, corsPlugin, bodyParserPlugin } from 'vegaa'

// Mock database
const db = {
1: { id: 1, name: 'Alice', email: 'alice@example.com' },
2: { id: 2, name: 'Bob', email: 'bob@example.com' }
}

async function main() {
// Register plugins
await vegaa.plugin(corsPlugin)
await vegaa.plugin(bodyParserPlugin)

console.log('✅ Plugins registered')

// GET all users
route('/users').get(() => {
return {
users: Object.values(db),
total: Object.keys(db).length
}
})

// GET single user
route('/users/:id').get((id) => {
const user = db[Number(id)]
if (!user) {
return { error: 'User not found' }
}
return user
})

// POST create user
route('/users').post((body) => {
if (!body?.name || !body?.email) {
return { error: 'Missing name or email' }
}

const id = Math.max(0, ...Object.keys(db).map(Number)) + 1
const newUser = { id, name: body.name, email: body.email }
db[id] = newUser

return { message: 'User created', user: newUser }
})

// PUT update user
route('/users/:id').put((params, body) => {
const id = Number(params.id)
if (!db[id]) {
return { error: 'User not found' }
}

db[id] = { ...db[id], ...body }
return { message: 'User updated', user: db[id] }
})

// DELETE user
route('/users/:id').delete((id) => {
const user = db[Number(id)]
if (!user) {
return { error: 'User not found' }
}

delete db[Number(id)]
return { message: `User ${id} deleted` }
})

// Start server
await vegaa.startVegaaServer({ port: 4000 })
console.log('✅ Server running on http://localhost:4000')
}

main().catch(err => {
console.error('💥 Server failed:', err)
process.exit(1)
})

Try It

Test It

# Get all users
curl http://localhost:4000/users

# Get single user
curl http://localhost:4000/users/1

# Create user
curl -X POST http://localhost:4000/users \
-H "Content-Type: application/json" \
-d '{"name":"Charlie","email":"charlie@example.com"}'

# Update user
curl -X PUT http://localhost:4000/users/1 \
-H "Content-Type: application/json" \
-d '{"name":"Alice Updated"}'

# Delete user
curl -X DELETE http://localhost:4000/users/1

Key Concepts

  • GET Routes - Parameters are flattened (id instead of params.id)
  • POST/PUT Routes - Parameters are grouped (params, body)
  • Body Parsing - bodyParserPlugin automatically parses JSON bodies
  • Error Handling - Return error objects for failed operations

Next Steps