Express.js Integration

Learn how to integrate Query-2jz with Express.js for powerful API development.

Getting Started

Query-2jz provides seamless integration with Express.js, allowing you to build powerful APIs with minimal configuration. Follow these steps to get started.

Installation

Install Query-2jz and the Express adapter

bash
npm install query-2jz @query-2jz/express

Basic Setup

Configure Query-2jz with your Express application

javascript
const express = require('express')
const { query-2jzExpress } = require('@query-2jz/express')
const query-2jz = require('query-2jz')

const app = express()

// Initialize Query-2jz
const query-2jzInstance = query-2jz({
  database: {
    type: 'postgresql',
    url: process.env.DATABASE_URL
  }
})

// Define your models
const User = query-2jzInstance.model('User', {
  id: { type: 'string', primary: true },
  name: { type: 'string', required: true },
  email: { type: 'string', required: true, unique: true }
})

// Mount Query-2jz API routes
app.use('/api', query-2jzExpress(query-2jzInstance))

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})

Advanced Configuration

Customize Query-2jz's behavior with Express.js middleware and advanced options.

Middleware Integration

Add authentication, logging, and other middleware

javascript
const express = require('express')
const { query-2jzExpress } = require('@query-2jz/express')
const query-2jz = require('query-2jz')

const app = express()

// Add middleware before Query-2jz
app.use('/api', (req, res, next) => {
  // Authentication middleware
  if (!req.headers.authorization) {
    return res.status(401).json({ error: 'Unauthorized' })
  }
  next()
})

// Add logging middleware
app.use('/api', (req, res, next) => {
  console.log(`${req.method} ${req.path}`)
  next()
})

// Initialize Query-2jz with custom options
const query-2jzInstance = query-2jz({
  database: {
    type: 'postgresql',
    url: process.env.DATABASE_URL
  },
  cache: {
    type: 'redis',
    url: process.env.REDIS_URL
  },
  realtime: {
    enabled: true,
    transport: 'websocket'
  }
})

// Mount with custom configuration
app.use('/api', query-2jzExpress(query-2jzInstance, {
  prefix: '/query-2jz',
  cors: true,
  rateLimit: {
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limit each IP to 100 requests per windowMs
  }
}))

Error Handling

Custom error handling for Query-2jz routes

javascript
// Custom error handler for Query-2jz routes
app.use('/api', (err, req, res, next) => {
  if (err.name === 'ValidationError') {
    return res.status(400).json({
      error: 'Validation failed',
      details: err.details
    })
  }
  
  if (err.name === 'NotFoundError') {
    return res.status(404).json({
      error: 'Resource not found'
    })
  }
  
  // Log unexpected errors
  console.error('Query-2jz Error:', err)
  res.status(500).json({
    error: 'Internal server error'
  })
})

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    query-2jz: query-2jzInstance.isConnected() 
  })
})

Production Considerations

Best practices for deploying Query-2jz with Express.js in production.

Performance

  • • Enable connection pooling
  • • Use Redis for caching
  • • Implement rate limiting
  • • Monitor query performance
  • • Use compression middleware
  • • Enable HTTP/2 support

Security

  • • Implement authentication
  • • Use HTTPS in production
  • • Validate input data
  • • Set up CORS properly
  • • Use environment variables
  • • Regular security updates

API Endpoints

Once integrated, Query-2jz automatically provides these RESTful endpoints for your models.

User Endpoints

GET /api/User - List all users
GET /api/User/:id - Get user by ID
POST /api/User - Create new user
PUT /api/User/:id - Update user
DELETE /api/User/:id - Delete user

Query Parameters

?where= - Filter results
?orderBy=field:asc - Sort results
?limit=10 - Limit results
?offset=20 - Skip results
?include=relation - Include relations