Node.js + Express

Build a complete REST API with Express.js and NexaDB binary protocol.

Project Setup

Terminal
# 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 nodemon

Configuration

.env

.env
PORT=3000
NEXA_HOST=localhost
NEXA_PORT=6970

config/database.js

config/database.js
const 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 };

Routes

routes/users.js

routes/users.js
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;

Main Server

server.js

server.js
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();

Running the App

Terminal
$nexadb start
$npm run dev
✓ Server running on http://localhost:3000

Complete!

You now have a fully functional REST API with NexaDB! This example demonstrates CRUD operations, error handling, and the binary protocol.