Build a complete REST API with Express.js and NexaDB binary protocol.
# Create project
mkdir nexadb-express-api
cd nexadb-express-api
npm init -y
# Install dependencies
npm install express nexaclient cors dotenv
npm install --save-dev nodemonPORT=3000
NEXA_HOST=localhost
NEXA_PORT=6970const NexaClient = require('nexaclient');
const db = new NexaClient({
host: process.env.NEXA_HOST || 'localhost',
port: parseInt(process.env.NEXA_PORT) || 6970,
username: 'root',
password: 'nexadb123',
timeout: 30000
});
async function connect() {
try {
await db.connect();
console.log('✓ Connected to NexaDB');
} catch (error) {
console.error('Failed to connect:', error);
process.exit(1);
}
}
module.exports = { db, connect };const express = require('express');
const router = express.Router();
const { db } = require('../config/database');
// GET all users
router.get('/', async (req, res) => {
try {
const { limit = 10 } = req.query;
const users = await db.query('users', {}, { limit: parseInt(limit) });
res.json({ success: true, data: users });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
// POST create user
router.post('/', async (req, res) => {
try {
const { name, email, age } = req.body;
if (!name || !email) {
return res.status(400).json({
success: false,
error: 'Name and email are required'
});
}
const result = await db.create('users', { name, email, age });
res.status(201).json({ success: true, data: result });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
module.exports = router;require('dotenv').config();
const express = require('express');
const cors = require('cors');
const { connect } = require('./config/database');
const usersRouter = require('./routes/users');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
app.use('/api/users', usersRouter);
async function start() {
await connect();
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
start();You now have a fully functional REST API with NexaDB! This example demonstrates CRUD operations, error handling, and the binary protocol.