Skip to content

itmsi/tracking-project-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

8 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Express.js API Boilerplate

Template lengkap untuk membangun REST API dengan Express.js yang sudah dilengkapi dengan berbagai fitur esensial untuk pengembangan aplikasi production-ready.

πŸš€ Fitur Utama

  • βœ… Example Module Template: Module contoh lengkap dengan CRUD, pagination, soft delete, validation
  • βœ… Database: PostgreSQL dengan Knex.js untuk query builder, migration, dan seeding
  • βœ… Authentication Ready: JWT middleware dan utilities (tinggal implement)
  • βœ… File Upload: Integrasi dengan AWS S3 dan MinIO untuk object storage
  • βœ… Email Service: Template email dengan Nodemailer
  • βœ… Message Queue: RabbitMQ untuk async task processing
  • βœ… API Documentation: Swagger/OpenAPI 3.0 dengan contoh lengkap
  • βœ… Security: Rate limiting, CORS, input validation, XSS protection
  • βœ… Monitoring: Prometheus metrics dan comprehensive logging
  • βœ… Internationalization: Multi-language support dengan i18n
  • βœ… Docker Support: Docker & Docker Compose untuk development dan production
  • βœ… CI/CD: Jenkins & Bitbucket Pipelines configuration

πŸ“‹ Prerequisites

Sebelum memulai, pastikan Anda sudah menginstall:

  • Node.js (v14 atau lebih baru)
  • PostgreSQL (v12 atau lebih baru)
  • Redis (opsional, untuk session storage)
  • Docker & Docker Compose (opsional, untuk containerization)

πŸ“¦ Installation

1. Clone Repository

git clone https://github.com/your-username/express-api-boilerplate.git
cd express-api-boilerplate

2. Install Dependencies

npm install

3. Environment Setup

Copy file environment example dan sesuaikan konfigurasi:

cp environment.example .env

Edit file .env dan sesuaikan dengan konfigurasi Anda:

# Application
APP_NAME=YourAppName
NODE_ENV=development
PORT=3000
APP_URL=http://localhost:3000

# Database
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=yourpassword
DB_NAME=yourdbname

# JWT
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=24h

# AWS S3 (optional)
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=
AWS_BUCKET=

# MinIO (optional)
MINIO_ENDPOINT=
MINIO_PORT=
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
MINIO_BUCKET=

# Email
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USER=
MAIL_PASSWORD=
MAIL_FROM=

# RabbitMQ (optional)
RABBITMQ_URL=amqp://localhost:5672

# Swagger
SWAGGER_ENABLED=true

4. Database Setup

Jalankan migration untuk membuat struktur database:

npm run migrate

Jalankan seeder untuk data awal (opsional):

npm run seed

5. Start Development Server

npm run dev

Server akan berjalan di http://localhost:3000

Akses dokumentasi API di http://localhost:3000/documentation

πŸ—οΈ Struktur Proyek

β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app.js                  # Express app configuration
β”‚   β”œβ”€β”€ server.js              # Server entry point
β”‚   β”œβ”€β”€ config/                # Konfigurasi aplikasi
β”‚   β”‚   β”œβ”€β”€ database.js        # Database configuration
β”‚   β”‚   β”œβ”€β”€ aws.js            # AWS S3 configuration
β”‚   β”‚   β”œβ”€β”€ minio.js          # MinIO configuration
β”‚   β”‚   β”œβ”€β”€ email.js          # Email configuration
β”‚   β”‚   β”œβ”€β”€ rabbitmq.js       # RabbitMQ configuration
β”‚   β”‚   └── prometheus.js     # Prometheus configuration
β”‚   β”œβ”€β”€ modules/               # Business logic modules
β”‚   β”‚   β”œβ”€β”€ example/          # πŸ“Œ Example module (TEMPLATE)
β”‚   β”‚   β”‚   β”œβ”€β”€ handler.js    # Controllers
β”‚   β”‚   β”‚   β”œβ”€β”€ postgre_repository.js  # DB operations
β”‚   β”‚   β”‚   β”œβ”€β”€ validation.js # Validation rules
β”‚   β”‚   β”‚   β”œβ”€β”€ index.js      # Routes
β”‚   β”‚   β”‚   └── README.md     # Documentation
β”‚   β”‚   └── helpers/          # Helper functions
β”‚   β”œβ”€β”€ middlewares/           # Custom middlewares
β”‚   β”‚   β”œβ”€β”€ token.js          # JWT verification
β”‚   β”‚   β”œβ”€β”€ validation.js     # Input validation
β”‚   β”‚   β”œβ”€β”€ rate-limiter.js   # Rate limiting
β”‚   β”‚   β”œβ”€β”€ recaptcha.js      # reCAPTCHA verification
β”‚   β”‚   └── fileUpload.js     # File upload handling
β”‚   β”œβ”€β”€ routes/               # API routes
β”‚   β”‚   β”œβ”€β”€ index.js          # Main routes
β”‚   β”‚   └── V1/               # API version 1
β”‚   β”œβ”€β”€ repository/           # Database layer
β”‚   β”‚   └── postgres/         # PostgreSQL specific
β”‚   β”‚       β”œβ”€β”€ migrations/   # Database migrations
β”‚   β”‚       └── seeders/      # Database seeders
β”‚   β”œβ”€β”€ utils/                # Utility functions
β”‚   β”‚   β”œβ”€β”€ response.js       # Standard API response
β”‚   β”‚   β”œβ”€β”€ logger.js         # Logging utility
β”‚   β”‚   β”œβ”€β”€ validation.js     # Validation helpers
β”‚   β”‚   β”œβ”€β”€ pagination.js     # Pagination helper
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ static/               # Swagger documentation
β”‚   β”‚   β”œβ”€β”€ index.js          # Swagger config
β”‚   β”‚   β”œβ”€β”€ path/             # API path definitions
β”‚   β”‚   └── schema/           # Schema definitions
β”‚   β”œβ”€β”€ templates/            # Email templates
β”‚   β”œβ”€β”€ views/                # View templates
β”‚   β”œβ”€β”€ listeners/            # RabbitMQ message listeners
β”‚   β”œβ”€β”€ scripts/              # Background scripts
β”‚   └── debug/                # Debug utilities
β”œβ”€β”€ docker/                   # Docker configurations
β”œβ”€β”€ public/                   # Static files
β”œβ”€β”€ logs/                     # Application logs
β”œβ”€β”€ uploads/                  # Uploaded files
β”œβ”€β”€ test/                     # Test files
β”œβ”€β”€ scripts/                  # Utility scripts
β”œβ”€β”€ docs/                     # Additional documentation
β”œβ”€β”€ .env                      # Environment variables (create from .env.example)
β”œβ”€β”€ package.json              # Dependencies
β”œβ”€β”€ QUICKSTART.md             # Quick start guide
β”œβ”€β”€ CONTRIBUTING.md           # Contribution guidelines
└── README.md                # This file

πŸ“ Cara Membuat Module Baru

πŸ’‘ Tip: Gunakan module example sebagai template! Copy dan customize sesuai kebutuhan.

Cara Cepat (Recommended)

# Copy module example sebagai template
cp -r src/modules/example src/modules/products

# Edit files di src/modules/products:
# - Ganti "example" dengan "product"  
# - Ganti "examples" dengan "products"
# - Customize fields sesuai kebutuhan

Cara Manual

1. Buat Folder Module

Buat folder baru di src/modules/namaModule/

2. Buat File-file Module

Struktur minimal sebuah module:

src/modules/namaModule/
β”œβ”€β”€ index.js              # Export semua handler
β”œβ”€β”€ handler.js            # Request handlers
β”œβ”€β”€ validation.js         # Input validation rules
└── postgre_repository.js # Database operations

Contoh handler.js:

const repository = require('./postgre_repository');
const { baseResponse, errorResponse } = require('../../utils/response');

const getAll = async (req, res) => {
  try {
    const data = await repository.findAll();
    return baseResponse(res, { data });
  } catch (error) {
    return errorResponse(res, error);
  }
};

const getById = async (req, res) => {
  try {
    const { id } = req.params;
    const data = await repository.findById(id);
    
    if (!data) {
      return errorResponse(res, { message: 'Data not found' }, 404);
    }
    
    return baseResponse(res, { data });
  } catch (error) {
    return errorResponse(res, error);
  }
};

const create = async (req, res) => {
  try {
    const data = await repository.create(req.body);
    return baseResponse(res, { data }, 201);
  } catch (error) {
    return errorResponse(res, error);
  }
};

const update = async (req, res) => {
  try {
    const { id } = req.params;
    const data = await repository.update(id, req.body);
    return baseResponse(res, { data });
  } catch (error) {
    return errorResponse(res, error);
  }
};

const remove = async (req, res) => {
  try {
    const { id } = req.params;
    await repository.remove(id);
    return baseResponse(res, { message: 'Data deleted successfully' });
  } catch (error) {
    return errorResponse(res, error);
  }
};

module.exports = {
  getAll,
  getById,
  create,
  update,
  remove
};

Contoh postgre_repository.js:

const db = require('../../config/database');

const TABLE_NAME = 'your_table_name';

const findAll = async () => {
  return await db(TABLE_NAME)
    .select('*')
    .where({ deleted_at: null })
    .orderBy('created_at', 'desc');
};

const findById = async (id) => {
  return await db(TABLE_NAME)
    .where({ id, deleted_at: null })
    .first();
};

const create = async (data) => {
  const [result] = await db(TABLE_NAME)
    .insert({
      ...data,
      created_at: db.fn.now(),
      updated_at: db.fn.now()
    })
    .returning('*');
  return result;
};

const update = async (id, data) => {
  const [result] = await db(TABLE_NAME)
    .where({ id })
    .update({
      ...data,
      updated_at: db.fn.now()
    })
    .returning('*');
  return result;
};

const remove = async (id) => {
  // Soft delete
  return await db(TABLE_NAME)
    .where({ id })
    .update({
      deleted_at: db.fn.now()
    });
};

module.exports = {
  findAll,
  findById,
  create,
  update,
  remove
};

Contoh validation.js:

const { body, param, query } = require('express-validator');

const createValidation = [
  body('name')
    .notEmpty()
    .withMessage('Name is required')
    .isLength({ min: 3 })
    .withMessage('Name must be at least 3 characters'),
  body('email')
    .notEmpty()
    .withMessage('Email is required')
    .isEmail()
    .withMessage('Email must be valid'),
];

const updateValidation = [
  param('id')
    .notEmpty()
    .withMessage('ID is required')
    .isUUID()
    .withMessage('ID must be valid UUID'),
  body('name')
    .optional()
    .isLength({ min: 3 })
    .withMessage('Name must be at least 3 characters'),
];

module.exports = {
  createValidation,
  updateValidation
};

Contoh index.js:

const express = require('express');
const router = express.Router();
const handler = require('./handler');
const { createValidation, updateValidation } = require('./validation');
const { verifyToken } = require('../../middlewares');
const { handleValidationErrors } = require('../../middlewares/validation');

router.get('/', verifyToken, handler.getAll);
router.get('/:id', verifyToken, handler.getById);
router.post('/', verifyToken, createValidation, handleValidationErrors, handler.create);
router.put('/:id', verifyToken, updateValidation, handleValidationErrors, handler.update);
router.delete('/:id', verifyToken, handler.remove);

module.exports = router;

3. Daftarkan Route

Edit file src/routes/V1/index.js:

const yourModule = require('../../modules/yourModule');

// ... existing code ...

routing.use(`${API_TAG}/your-endpoint`, yourModule);

4. Buat Migration

Buat file migration untuk table:

npm run migrate:make create_your_table

Edit file migration di src/repository/postgres/migrations/:

exports.up = function(knex) {
  return knex.schema.createTable('your_table_name', (table) => {
    table.uuid('id').primary().defaultTo(knex.raw('uuid_generate_v4()'));
    table.string('name').notNullable();
    table.string('email').unique();
    table.text('description');
    table.timestamp('created_at').defaultTo(knex.fn.now());
    table.timestamp('updated_at').defaultTo(knex.fn.now());
    table.timestamp('deleted_at').nullable();
  });
};

exports.down = function(knex) {
  return knex.schema.dropTable('your_table_name');
};

Jalankan migration:

npm run migrate

πŸ“– Example API Endpoints

Boilerplate ini sudah include module example sebagai template dengan endpoints berikut:

Get All Examples

GET /api/examples?page=1&limit=10

Get Example by ID

GET /api/examples/:id

Create Example

POST /api/examples
Content-Type: application/json

{
  "name": "Example Name",
  "description": "Description",
  "status": "active"
}

Update Example

PUT /api/examples/:id
Content-Type: application/json

{
  "name": "Updated Name"
}

Delete Example

DELETE /api/examples/:id

Restore Example

POST /api/examples/:id/restore

πŸ“š Full API Documentation: http://localhost:3000/documentation

πŸ” Authentication (Ready to Implement)

Boilerplate sudah include JWT middleware. Untuk menggunakannya:

1. Uncomment di route:

const { verifyToken } = require('../../middlewares');

router.get('/', verifyToken, handler.getAll);

2. Tambahkan header Authorization:

Authorization: Bearer your-jwt-token

πŸ’‘ Tip: Lihat src/middlewares/token.js untuk JWT verification logic

πŸ“š API Documentation

Dokumentasi API tersedia via Swagger UI. Akses di:

http://localhost:3000/documentation

Untuk menambahkan dokumentasi API Anda, edit file:

  • src/static/path/yourModule.js - untuk endpoint paths
  • src/static/schema/yourModule.js - untuk schema definitions

🐳 Docker

Development

docker-compose -f docker-compose.dev.yml up

Production

docker-compose -f docker-compose.server.yml up -d

πŸ“Š Monitoring

Prometheus Metrics

Metrics tersedia di endpoint:

http://localhost:3000/metrics

Logs

Log tersimpan di folder logs/:

  • logs/application/ - Application logs
  • logs/listener/ - RabbitMQ listener logs

πŸ§ͺ Testing

npm test

πŸ› οΈ Available Scripts

  • npm start - Jalankan server production
  • npm run dev - Jalankan server development dengan nodemon
  • npm run migrate - Jalankan database migrations
  • npm run migrate:rollback - Rollback migration terakhir
  • npm run migrate:make <name> - Buat file migration baru
  • npm run seed - Jalankan database seeders
  • npm run seed:make <name> - Buat file seeder baru
  • npm run consumer - Jalankan RabbitMQ consumer
  • npm test - Jalankan tests

πŸ“– Dependencies

Core

  • express - Web framework
  • pg - PostgreSQL client
  • knex - SQL query builder
  • jsonwebtoken - JWT implementation
  • bcrypt - Password hashing

Utilities

  • joi - Schema validation
  • express-validator - Request validation
  • morgan - HTTP request logger
  • winston - Logging library
  • moment - Date manipulation
  • uuid - UUID generator

File Upload

  • multer - Multipart/form-data handling
  • aws-sdk - AWS S3 client
  • minio - MinIO client
  • sharp - Image processing

Others

  • swagger-ui-express - API documentation
  • prom-client - Prometheus metrics
  • amqplib - RabbitMQ client
  • nodemailer - Email sending
  • i18n - Internationalization
  • compression - Response compression
  • xss-clean - XSS protection
  • express-rate-limit - Rate limiting

🀝 Contributing

Contributions are welcome! Silakan buat pull request atau issue untuk saran dan perbaikan.

πŸ“„ License

MIT License - lihat file LICENSE untuk detail.

πŸ‘¨β€πŸ’» Author

Your Name

πŸ™ Acknowledgments

Boilerplate ini dibuat dengan menggabungkan best practices dari berbagai sumber dan pengalaman development.

πŸ“ž Support

Untuk pertanyaan atau dukungan:


Made with ❀️ for the developer community

About

tracking-project-api express js, postgresql, sweger

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages