Node.js API

שרת REST API עם Node.js ו-MongoDB

גרסה 2.3.0 עודכן: 12/02/2025

סקירה כללית

שרת REST API מודרני המבוסס על Node.js ו-Express, עם MongoDB כבסיס נתונים. כולל אותנטיקציה, הרשאות, תיעוד API מובנה, ומערכת ניטור.

תכונות עיקריות

  • REST API מלא
  • JWT Authentication
  • Swagger Documentation
  • Rate Limiting

הוראות התקנה


# Clone the repository
git clone https://github.com/devops-israel/nodejs-api

# Install dependencies
npm install

# Set environment variables
cp .env.example .env

# Start development server
npm run dev

# Run tests
npm test
                    

נתיבי API


// Authentication Routes
POST   /api/auth/register     - הרשמת משתמש חדש
POST   /api/auth/login        - התחברות למערכת
POST   /api/auth/refresh      - חידוש טוקן

// User Routes
GET    /api/users            - קבלת כל המשתמשים
GET    /api/users/:id        - קבלת משתמש ספציפי
PUT    /api/users/:id        - עדכון משתמש
DELETE /api/users/:id        - מחיקת משתמש

// Product Routes
GET    /api/products         - קבלת כל המוצרים
POST   /api/products         - יצירת מוצר חדש
GET    /api/products/:id     - קבלת מוצר ספציפי
PUT    /api/products/:id     - עדכון מוצר
DELETE /api/products/:id     - מחיקת מוצר
                    

מודלים


// User Model
const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    role: {
        type: String,
        enum: ['user', 'admin'],
        default: 'user'
    }
});

// Product Model
const productSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    description: String,
    category: {
        type: String,
        required: true
    }
});
                    

Middleware


// Authentication Middleware
const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '');
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const user = await User.findById(decoded.id);
        
        if (!user) {
            throw new Error();
        }
        
        req.user = user;
        next();
    } catch (error) {
        res.status(401).send({ error: 'Please authenticate.' });
    }
};

// Rate Limiting Middleware
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100 // limit each IP to 100 requests per windowMs
});
                    

ניטור וביצועים

  • Express Prometheus Metrics
  • Morgan Access Logs
  • Winston Logger
  • Performance Monitoring