1.0.9 • Published 8 months ago

nest-lite v1.0.9

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

Nest Lite

Nest Lite is a lightweight package designed to simplify the process of creating APIs in TypeScript with Express.js. This package provides decorators and utilities to easily define controllers, models, repositories, and routes. It offers a developer-friendly approach to building web APIs with fewer boilerplate and enhanced readability.

Getting Started

Folder Structure Driven Routing

Nest Lite leverages folder structure-driven routing, where the organization of your controller files directly maps to the URL structure of your API. This makes your API endpoints more intuitive and organized.

Here's an example of a sample folder structure:

  • src
    • controllers
      • users
        • user-controller.ts
      • products
        • product-controller.ts
    • repositories
      • users-repository.ts
    • dtos
      • user.dtos.ts

In this example, the users and products folders automatically provide route prefixes for the API endpoints defined within their respective controllers.

Controller Methods and Automatic Parameter Scanning

One of the key features of Nest Lite is automatic parameter scanning. Controller method parameters' names are automatically scanned, eliminating the need for explicit decorators like @Body() or @Query(). This simplifies your code and improves readability.

import { Get, Post, Put, Delete } from 'nest-lite';

export class UserController {
  @Get('/users/:id') // Dynamic route path
  async getHandler(params: any) {
    // Your GET request handler logic here
  }

  @Post('/users')
  async postHandler(body: any) {
    // Your POST request handler logic here
  }

  @Put('/users/:id') // Dynamic route path
  async putHandler(params: any, body: any) {
    // Your PUT request handler logic here
  }

  @Delete('/users/:id') // Dynamic route path
  async deleteHandler(params: any) {
    // Your DELETE request handler logic here
  }
}

DTOs and Class Validators

DTOs (Data Transfer Objects) play a crucial role in shaping request and response payloads. They help standardize data formats and validate incoming data. Nest Lite allows you to define DTOs in a dedicated dtos folder for use in your controllers. Additionally, you can use class validators for input validation.

Here's an example of a DTO definition and its usage with class validators:

// user.dtos.ts
import { IsString, IsEmail } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;

  @IsEmail()
  email: string;
}

// Using the CreateUserDto in a controller
import { Post } from 'nest-lite';
import { UserRepository } from '../repositories/users-repository'; // Import your custom repository
import { CreateUserDto } from '../dtos/user.dtos'; // Import your DTO

export class UserController {
  @Post('/users')
  async createUser(body: CreateUserDto) {
    // Access the data from the body DTO
    const newUser = await UserRepository.create({
      name: body.name,
      email: body.email,
    });

    // Your POST request handler logic here
  }
}

Custom Repository

Nest Lite supports the use of custom repositories for data access. These repositories are designed to accept only schema classes decorated with Prop.

Here's an example of a custom repository:

// users-repository.ts
import { BaseRepository } from 'nest-lite';

// Define the User schema using decorators
class UserSchema {
  name: string;
  email: string;
}

// Define the custom repository for User
export const UserRepository = new BaseRepository(UserSchema);

// Using the UserRepository in a controller
import { Get } from 'nest-lite';

export class UserController {
  @Get('/users/:id')
  async getUser(params: any) {
    // Fetch a user by ID using the custom repository
    const user = await UserRepository.fetchOne({ searchParams: { _id: params.id } });

    // Your GET request handler logic here
  }
}

Controllers Are Auto Imported

Nest Lite automatically imports and registers controllers with Express.js. There's no need for explicit imports of controllers in your main app file. Instead, create an app.ts file to initialize your Express application and use the provided registerControllers function to discover and register all controllers automatically.

Here's an example of an app.ts file:

import express from 'express';
import { registerControllers } from 'nest-lite';
import * as path from 'path';

const app = express();
const port = 3000;

// Register controllers automatically from the 'controllers' folder
const controllerFolderPath = path.join(__dirname, 'controllers');
registerControllers(app, controllerFolderPath);

// Start the Express server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

With this setup, all controllers from the controllers folder are automatically imported and registered with your Express application.

Leveraging Express Features Over NestJS Modules and Dependency Injection

Nest Lite encourages a simplified approach to building APIs. It avoids the complexity of NestJS modules and dependency injection, allowing you to work more closely with Express features.

You can seamlessly use other Express middleware in your application, define custom routes, serve static files, and leverage any other Express feature you need. This simplicity gives you more control over your application's structure and behavior, making it easier to build APIs according to your requirements.

1.0.9

8 months ago

1.0.8

8 months ago

1.0.7

8 months ago

1.0.5

8 months ago

1.0.4

8 months ago

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago