1.0.7 • Published 5 months ago

siteweaver-service-layer v1.0.7

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

Project Overview

SiteWeaver-Service Layer

The SiteWeaver-Service Layer is a robust Node.js backend project template with built-in multi-tenancy support, designed to help you quickly set up enterprise-grade applications. Includes a CLI tool for generating boilerplate code with database, ORM, and other essential configurations.

MIT License

Table of Contents

Features

  • šŸ¢ Multi-tenancy: Built-in support with isolated databases per tenant
  • šŸ› ļø CLI Tool: Quick project generation with customizable templates
  • šŸ“Š Database: PostgreSQL support with Knex.js ORM
  • šŸ—ļø Architecture: Clean, layered architecture with clear separation of concerns
  • šŸ”’ Security: Built-in authentication, authorization, and data protection
  • ✨ Developer Experience: TypeScript, ESLint, Prettier, and Jest configured
  • šŸ“ Documentation: Comprehensive API documentation and usage guides
  • šŸ“ Logger: Built-in logging with Winston and Morgan.

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js: Version 20 or higher.
  • npm: Node package manager.
  • PostgreSQL: Installed and running (if using the default database).

Installation

Install the CLI tool globally:

npm install -g siteweaver-service-layer

Create a new project:

siteweaver-service-layer create

Follow the prompts to configure your project:

  • Enter the project name.
  • Configure the database (name, host, port, username, password).
  • Choose the ORM (default: Knex.js).

Navigate to the project directory:

cd <project-name>

Install dependencies:

npm install

Usage

Start the Project

Build the project:

npm run build

Run the project:

npm start

Run Migrations

To apply database migrations:

npm run migrate:api

Development Mode

For development, use:

npm run dev

This will:

  • Stop any running instances.
  • Clean the dist folder.
  • Build the project.
  • Start the server in watch mode.

Project Structure

<project-name>/
ā”œā”€ā”€ dist/                  # Compiled TypeScript files
ā”œā”€ā”€ bin/                   # Binary executables
ā”œā”€ā”€ package/               # Project packaging scripts
ā”œā”€ā”€ templates/             # Templates for project generation
ā”œā”€ā”€ test/                  # Test files
ā”œā”€ā”€ log/                   # Log files
ā”œā”€ā”€ cmd/                   # Command line interface files
ā”œā”€ā”€ src/                   # Source files
│   ā”œā”€ā”€ config/            # Database configurations and migrations
│   ā”œā”€ā”€ app/               # Main application files
│   ā”œā”€ā”€ routes/            # Route definitions
│   ā”œā”€ā”€ validations/       # Validation logic
│   ā”œā”€ā”€ constant/          # Constant values
│   ā”œā”€ā”€ middleware/        # Middleware functions
│   ā”œā”€ā”€ services/          # Service layer
│   ā”œā”€ā”€ factories/         # Factory functions
│   ā”œā”€ā”€ repositories/      # Data access layer
│   ā”œā”€ā”€ models/            # Database models
│   ā”œā”€ā”€ db/                # Database setup
│   ā”œā”€ā”€ enums/             # Enums used in the project
│   ā”œā”€ā”€ interfaces/        # Interface definitions
│   ā”œā”€ā”€ types/             # Type definitions
│   ā”œā”€ā”€ utils/             # Utility functions
│   ā”œā”€ā”€ graphql/           # GraphQL schema and resolvers
│   ā”œā”€ā”€ generator/         # Code generation scripts
│   ā”œā”€ā”€ helpers/           # Helper functions
│   └── app.bootstrap.ts   # Entry point for the application
ā”œā”€ā”€ .env                   # Environment variables
ā”œā”€ā”€ .gitignore             # Git ignore file
ā”œā”€ā”€ package.json           # Project dependencies and scripts
└── README.md              # Project documentation

Scripts

ScriptDescription
npm run typescriptRun the project in development mode using ts-node.
npm run buildCompile TypeScript files and run migrations.
npm startStart the compiled application.
npm run devStop, clean, build, and start in development mode.
npm run migrateRun database migrations.
npm run testRun tests using Jest.
npm run lintLint the codebase using ESLint.
npm run formatFormat the codebase using Prettier.

Database Configuration

The project uses PostgreSQL by default. Configure the database in the .env file:

DB_HOST=localhost
DB_PORT=5432
DB_USER=root
DB_PASSWORD=yourpassword
DB_NAME=yourdbname

ORM Configuration

The project uses Knex.js as the ORM. The configuration file is located at knexfile.ts. Modify it as needed.

Testing

The project includes Jest for testing. To run tests:

npm run test

Linting and Formatting

ESLint: Ensures code quality and consistency.

npm run lint

Prettier: Formats the codebase.

npm run format

Contributing

Contributions are welcome! Follow these steps:

  1. Fork the repository.
  2. Create a new branch:
    git checkout -b feature/YourFeature
  3. Commit your changes:
    git commit -m 'Add some feature'
  4. Push to the branch:
    git push origin feature/YourFeature
  5. Open a pull request.

Architecture Design

The project follows a Layered Architecture pattern, which separates concerns into distinct layers, enhancing maintainability and scalability. The primary layers include:

  • Presentation Layer: Handles user interactions and API requests.
  • Business Logic Layer: Contains the core application logic, including services for managing tenants and permissions.
  • Data Access Layer: Interacts with the database, managing data retrieval and persistence.

This design allows for clear separation of concerns, making it easier to modify or extend individual components without affecting the entire system.


Classes and Interfaces

Core Classes

  • NodeJSStarterKit: Responsible for initializing the project and generating necessary files.
  • BoilerplateGenerator: Creates the boilerplate structure for new projects, including configuration files.
  • EnvFileCreator: Prepares the .env file content dynamically based on user input.
  • Database: Manages database connections and migrations.

Interfaces

  • Answers: Defines the structure for user input during project initialization.
  • PackageJson: Represents the structure of the package.json file, ensuring type safety.

Relationships

Classes interact through well-defined interfaces, promoting loose coupling and enhancing testability.


Exception Handling

The project employs a centralized error handling strategy. Custom exceptions are defined for various error scenarios, allowing for consistent error responses across the application. The logging mechanism captures errors and important events, facilitating debugging and monitoring.

Key Features

  • Custom Error Classes: Specific exceptions for different error types.
  • Logging: Utilizes a logging library to capture and store error details.

Class Methods & Object-Oriented Concepts

The project leverages several object-oriented programming concepts:

  • Static Methods: Used for utility functions that do not require instance state.
  • Inheritance: Classes like RoleController and PermissionController inherit from a base controller class, promoting code reuse.
  • Encapsulation: Private properties and methods are used to protect internal state and behavior.
  • Polymorphism: Interfaces allow for different implementations of methods, enhancing flexibility.

Environment Configuration

Configuration settings are managed through environment variables, loaded from a .env file. Key configurations include database connection details, API keys, and application settings.

Dependency Management

Dependencies are managed using npm, with a package.json file that lists all required packages and their versions.


API Documentation

The project exposes a RESTful API for managing tenants, roles, and permissions. Key endpoints include:

  • POST /api/entity/create: Create a new entity.
  • POST /api/tenants: Create a new tenant.
  • GET /api/tenants/:id: Retrieve tenant details.
  • POST /api/roles: Create a new role.
  • GET /api/roles: List all roles.

Request/Response Formats

Requests and responses are formatted in JSON, ensuring consistency and ease of use.

Authentication Mechanisms

JWT (JSON Web Tokens) are used for securing API endpoints, ensuring that only authorized users can access certain resources.


Multi-Tenancy Support

The system is designed to handle multiple tenants through database segregation. Each tenant has its own database, ensuring data isolation and security. Access control mechanisms are in place to restrict data access based on tenant identity.


Security Features

Security is a top priority in the design of this application. Key practices include:

  • Authentication: Secure login mechanisms using JWT.
  • Authorization: Role-based access control to restrict user actions.
  • Data Protection: Encryption of sensitive data both in transit and at rest.

Scalability & Performance Considerations

The architecture is designed to scale horizontally, allowing for the addition of more servers as the user base grows. Performance optimizations include:

  • Caching: Implementing caching strategies to reduce database load.
  • Load Balancing: Distributing incoming requests across multiple servers to ensure high availability.

This README provides a comprehensive overview of the SiteWeaver-Service Layer project, detailing its architecture, key components, and technical considerations. For further information, please refer to the project's documentation or source code.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Author

šŸ“§ Email me