0.0.46 β€’ Published 4 months ago

@tspvivek/baasix v0.0.46

Weekly downloads
-
License
SEE LICENSE IN LI...
Repository
-
Last release
4 months ago

Baasix

A flexible, feature-rich headless CMS with dynamic schema management and comprehensive API capabilities.

Overview

Baasix is a powerful backend-as-a-service platform that enables rapid development of web and mobile applications. It provides a dynamic schema management system, built-in authentication and authorization, file handling capabilities, and much more.

Core Features

  • πŸ”„ Dynamic Schema Management - Create, modify, and delete data models on-the-fly
  • πŸ” Authentication & Authorization - Built-in user management with JWT, session-based auth, and magic links
  • πŸ‘₯ Multi-tenant Support - Isolate data across different tenants in the same application
  • πŸ“ File Handling & Storage - Support for local and S3-compatible storage providers
  • πŸ” Full-text Search - Automatic indexing and search capabilities across your data
  • πŸ—ΊοΈ PostGIS Support - Geospatial data types and operations
  • πŸ’Ύ Redis Caching - High-performance caching for improved response times
  • πŸ“§ Email Services - Integrated email capabilities for user notifications
  • 🎣 Extensible Hook System - Add custom logic at various points in the request lifecycle
  • πŸ“… Scheduled Tasks - Run background processes and cron jobs
  • πŸ”Œ REST API - Comprehensive API endpoints for all operations
  • πŸ”„ Real-time Updates - Optional Socket.IO integration
  • πŸ§ͺ Comprehensive Testing Suite - Ensures reliability and stability

Installation

Using NPM Package

npm install @tspvivek/baasix

Quick Start

Create a server.js file:

import { startServer } from "@tspvivek/baasix";

if (require.main === module) {
    const app = startServer();
}

Run your server:

node server.js

Prerequisites

  • Node.js (v14+)
  • PostgreSQL (v11+)
  • Redis (optional, for caching)

Configuration

Environment Variables

Create a .env file in your project root with the following options:

# Server Configuration
PORT=8056
NODE_ENV=development

# Database
DB_CLIENT=postgres
DB_HOST=localhost
DB_PORT=5432
DB_NAME=baasix
DB_USER=postgres
DB_PASSWORD=postgres
DB_POSTGIS=true

# Authentication
SECRET_KEY=your-secret-key
COOKIE_SECRET=your-cookie-secret
ACCESS_TOKEN_EXPIRES_IN=3600
REFRESH_TOKEN_EXPIRES_IN=604800
PUBLIC_REGISTRATION=true
DEFAULT_ROLE_REGISTERED=user
AUTH_APP_URL=http://localhost:3000

# Multi-tenant Support
MULTI_TENANT=false
TENANT_FIELD=tenant_Id

# Cache Configuration
CACHE_ENABLED=true
CACHE_TTL=30000
CACHE_REDIS_URL=redis://localhost:6379
CACHE_SIZE_GB=1

# Rate Limiting
RATE_LIMIT=100
RATE_LIMIT_INTERVAL=5000

# Storage Services
STORAGE_SERVICES_ENABLED=local,s3
STORAGE_DEFAULT_SERVICE=local
LOCAL_STORAGE_PATH=./uploads
LOCAL_STORAGE_DRIVER=LOCAL

# S3 Configuration
S3_STORAGE_ACCESS_KEY_ID=your-access-key
S3_STORAGE_SECRET_ACCESS_KEY=your-secret-key
S3_STORAGE_REGION=your-region
S3_STORAGE_BUCKET=your-bucket
S3_STORAGE_ENDPOINT=your-endpoint

# Email Configuration
MAIL_SENDERS_ENABLED=smtp
MAIL_DEFAULT_SENDER=smtp
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=your-email
SMTP_PASS=your-password
SMTP_FROM_ADDRESS=noreply@example.com

# Real-time Support
SOCKET_ENABLED=false
SOCKET_PATH=/socket.io

Docker Deployment

You can also run Baasix using Docker:

docker build -t baasix .
docker run -p 8056:8056 --env-file .env baasix

Or with docker-compose:

version: '3'
services:
  baasix:
    build: .
    ports:
      - "8056:8056"
    env_file: .env
    depends_on:
      - postgres
      - redis
  postgres:
    image: postgis/postgis:13-3.1
    ports:
      - "5432:5432"
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: baasix
    volumes:
      - postgres_data:/var/lib/postgresql/data
  redis:
    image: redis:6
    ports:
      - "6379:6379"
volumes:
  postgres_data:

API Reference

Authentication

Baasix provides multiple authentication methods:

Registration

POST /auth/register
Content-Type: application/json

{
  "firstName": "John",
  "lastName": "Doe",
  "email": "john@example.com",
  "password": "securePassword123",
  "authMode": "jwt"  // Optional: "jwt" (default) or "cookie"
}

Login

POST /auth/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "securePassword123",
  "authMode": "jwt"  // Optional: "jwt" (default) or "cookie"
}

Magic Link Authentication

POST /auth/magiclink
Content-Type: application/json

{
  "email": "john@example.com",
  "link": "http://localhost:3000", // The app URL where user will be redirected
  "mode": "link"  // "link" or "code"
}

Get Current User

GET /auth/me
Authorization: Bearer <token>

Logout

GET /auth/logout
Authorization: Bearer <token>

Dynamic Schema Management

Create or update a schema:

POST /schemas
Authorization: Bearer <token>
Content-Type: application/json

{
  "collectionName": "products",
  "schema": {
    "name": "Product",
    "timestamps": true,
    "paranoid": true,
    "fields": {
      "id": { 
        "type": "UUID", 
        "primaryKey": true, 
        "defaultValue": { "type": "UUIDV4" } 
      },
      "name": { 
        "type": "String", 
        "allowNull": false 
      },
      "price": { 
        "type": "Double", 
        "allowNull": false 
      },
      "description": { 
        "type": "Text" 
      },
      "category_id": { 
        "type": "UUID" 
      },
      "category": {
        "relType": "BelongsTo",
        "target": "categories",
        "foreignKey": "category_id"
      }
    },
    "indexes": [
      {
        "fields": ["name"],
        "unique": true,
        "name": "product_name_unique"
      }
    ]
  }
}

Item Management

Baasix provides a standardized CRUD API for all collections:

Create Item

POST /items/:collection
Authorization: Bearer <token>
Content-Type: application/json

{
  "field1": "value1",
  "field2": "value2"
}

Get Items

GET /items/:collection?filter[field]=value&sort=field&page=1&limit=10
Authorization: Bearer <token>

Get One Item

GET /items/:collection/:id
Authorization: Bearer <token>

Update Item

PATCH /items/:collection/:id
Authorization: Bearer <token>
Content-Type: application/json

{
  "field1": "updated value"
}

Delete Item

DELETE /items/:collection/:id
Authorization: Bearer <token>

File Management

Upload a file:

POST /files
Authorization: Bearer <token>
Content-Type: multipart/form-data

file: [binary data]
title: File Title
description: File description

Get file metadata:

GET /files/:id
Authorization: Bearer <token>

Download a file:

GET /assets/:id
Authorization: Bearer <token>

Permissions

Baasix has a robust permissions system:

POST /permissions
Authorization: Bearer <token>
Content-Type: application/json

{
  "role_Id": "user-role-id",
  "collection": "products",
  "action": "read",  // create, read, update, delete
  "fields": "*",     // "*" for all fields or ["field1", "field2"]
  "conditions": {    // Optional filtering conditions
    "owner_id": {"$CURRENT_USER": "id"}
  }
}

Advanced Features

Data Types

Baasix supports a wide range of field types:

  • Basic: String, Integer, BigInt, Decimal, Real, Double, Boolean, Text
  • Date/Time: DateTime, Date
  • JSON: JSON, JSONB
  • IDs: UUID, TOKEN
  • Special: ENUM, VIRTUAL, CiText (case-insensitive text)
  • Arrays: Arrays of any primitive type
  • Ranges: Integer, DateTime, Double, Decimal, and Date ranges
  • Geospatial: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection, Geography

Extensions System

Baasix has three types of extensions:

1. Hook Extensions

// extensions/baasix-hook-my-hook/index.js
export default {
  id: 'my-product-hooks',
  name: 'My Product Hooks',
  description: 'Custom hooks for products',
  
  events: [
    {
      collection: 'products',
      action: 'items.create.before',
      handler: async (data, context) => {
        // Modify data before creation
        data.createdBy = context.accountability.user?.id;
        return data;
      }
    }
  ]
};

2. Endpoint Extensions

// extensions/baasix-endpoint-my-api/index.js
export default {
  id: 'my-custom-api',
  name: 'My Custom API',
  
  register: ({ app, services, database }) => {
    app.get('/custom-endpoint', async (req, res) => {
      try {
        // Your custom logic
        res.json({ data: { message: 'Custom endpoint response' } });
      } catch (error) {
        res.status(500).json({ error: { message: error.message } });
      }
    });
  }
};

3. Schedule Extensions

// extensions/baasix-schedule-my-task/index.js
export default {
  id: 'daily-cleanup',
  name: 'Daily Cleanup Task',
  
  schedules: [
    {
      id: 'cleanup-files',
      schedule: '0 0 * * *', // Run at midnight every day
      handler: async (context) => {
        const { database } = context;
        const { Op } = database.Sequelize;
        
        // Delete temporary files older than 7 days
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - 7);
        
        await database.models.baasix_Files.destroy({
          where: {
            temporary: true,
            createdAt: { [Op.lt]: cutoffDate }
          }
        });
      }
    }
  ]
};

Testing

Baasix includes a comprehensive test suite. To run tests:

npm test

To run a specific test file:

npm test -- auth.test.js

Documentation

For more comprehensive documentation, see the /documentation folder in the project root:

License

See the LICENSE file for details.

0.0.43

4 months ago

0.0.44

4 months ago

0.0.45

4 months ago

0.0.46

4 months ago

0.0.40

5 months ago

0.0.41

5 months ago

0.0.42

4 months ago

0.0.39

5 months ago

0.0.38

5 months ago

0.0.37

5 months ago

0.0.33

5 months ago

0.0.34

5 months ago

0.0.35

5 months ago

0.0.36

5 months ago

0.0.32

5 months ago

0.0.24

6 months ago

0.0.25

6 months ago

0.0.30

5 months ago

0.0.31

5 months ago

0.0.26

6 months ago

0.0.27

6 months ago

0.0.28

6 months ago

0.0.29

6 months ago

0.0.22

6 months ago

0.0.23

6 months ago

0.0.20

6 months ago

0.0.21

6 months ago

0.0.18

6 months ago

0.0.19

6 months ago

0.0.16

6 months ago

0.0.17

6 months ago

0.0.13

7 months ago

0.0.14

7 months ago

0.0.15

7 months ago

0.0.12

7 months ago

0.0.10

7 months ago

0.0.11

7 months ago

0.0.3

7 months ago

0.0.2

7 months ago

0.0.9

7 months ago

0.0.8

7 months ago

0.0.5

7 months ago

0.0.4

7 months ago

0.0.7

7 months ago

0.0.6

7 months ago

0.0.1

8 months ago