npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nestjs-library/crud

v0.12.9

Published

Automatically generate CRUD Rest API based on NestJS and TypeOrm

Downloads

136

Readme

@nestjs-library/crud

This is a Typescript library that provides a NestJS decorator which automatically generates CRUD routes of a controller for given TypeORM entity. The decorator generates endpoints for not only create, retrieve one, retrieve many, update, delete but also upsert, recover and search operations for the entity.

Features

  • Automatically generates CRUD routes for a given TypeORM entity
  • Automatically generates swagger for generated routes
  • Supports pagination, sorting, filtering, relation, searching, upserting, recovering and soft deleting
  • Supports complex search criteria(LIKE, ILIKE, BETWEEN, IN, NULL, ?, @>, JSON_CONTAINS)
  • Supports strong validation by using class-validator
  • Supports saving author information for mutating operations(Create, Update, Upsert, Delete and Recover)
  • Supports adding decorators, interceptors to each routes in Controller for customizing
  • Supports customizing swagger response

Installation

# npm
npm install @nestjs-library/crud

# yarn
yarn add @nestjs-library/crud

# pnpm
pnpm add @nestjs-library/crud

Usage

Step 1: Define a TypeORM entity

In order to use the Crud decorator, you need to define a TypeORM entity first. The following example defines a User entity with the following properties.

import { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    username: string;

    @Column()
    email: string;
}

Step 2: Create Service and Controller

Create a NestJS service and controller with a TypeORM entity. The service needs to extend the CrudService class and the controller needs to implement the CrudController interface.

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CrudService } from '@nestjs-library/crud';
import { Repository } from 'typeorm';

import { User } from './user.entity';

@Injectable()
export class UserService extends CrudService<User> {
    constructor(@InjectRepository(User) repository: Repository<User>) {
        super(repository);
    }
}
import { Controller } from '@nestjs/common';
import { Crud, CrudController } from '@nestjs-library/crud';

import { User } from './user.entity';
import { UserService } from './user.service';

@Crud({ entity: User })
@Controller('users')
export class UserController implements CrudController<User> {
    constructor(public readonly crudService: UserService) {}
}

Step 3: Add Service, Controller and TypeORM module to your module

In your NestJS module, add Service, Controller and TypeORM module to providers, controllers, imports array respectively.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { User } from './user.entity';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@Module({
    imports: [TypeOrmModule.forFeature([User])],
    controllers: [UserController],
    providers: [UserService],
})
export class UserModule {}

Step 4: Access the generated endpoints

After the module initializes, it will generate the following CRUD endpoints:

  • GET /users - retrieves a list of users with pagination
  • GET /users/:id - retrieves a single user by ID
  • POST /users - creates single or multiple users
  • PATCH /users/:id - updates an existing user by ID
  • DELETE /users/:id - deletes an existing user by ID
  • PUT /users/:id - upserts (update or create) an existing user by ID
  • POST /users/search - retrieves a list of users based on complex search criteria
  • POST /users/:id/recover - recovers a soft deleted user by ID

Configuration

The Crud decorator supports the following configuration options:

entity

(required) The TypeORM entity that the controller operates on.

routes

(optional) You can configure each route by specifying the routes option.

For example, if you want to set the default pagination size for a search route, you can specify option as below.

@Crud({
    entity: User,
    routes: {
        search: { numberOfTake: 5 },
    },
})

Every route has the following base options.

import { NestInterceptor, Type } from '@nestjs/common';

interface RouteBaseOption {
    decorators?: Array<PropertyDecorator | MethodDecorator>;
    interceptors?: Array<Type<NestInterceptor>>;
    swagger?: {
        hide?: boolean;
        response?: Type<unknown>;
    };
    exclude?: string[];
}

CREATE, UPDATE, DELETE, UPSERT, and RECOVER routes can have the following options.

interface SaveOptions {
    listeners?: boolean;
}

And each route has its own options as below.

READ_ONE

interface ReadOneOptions {
    params?: string[];
    softDelete?: boolean;
    relations?: false | string[];
}

READ_MANY

import { Sort, PaginationType } from 'src/lib/interface';

interface ReadManyOptions {
    sort?: Sort | `${Sort}`;
    paginationType?: PaginationType | `${PaginationType}`;
    numberOfTake?: number;
    relations?: false | string[];
    softDelete?: boolean;
    paginationKeys?: string[];
}

SEARCH

import { PaginationType } from 'src/lib/interface';

interface SearchOptions {
    paginationType?: PaginationType | `${PaginationType}`;
    numberOfTake?: number;
    limitOfTake?: number;
    relations?: false | string[];
    softDelete?: boolean;
    paginationKeys?: string[];
}

CREATE

import { Type } from '@nestjs/common';
import { Author } from 'src/lib/interface';

interface CreateOptions {
    swagger?: {
        body?: Type<unknown>;
    };
    author?: Author;
}

UPDATE

import { Type } from '@nestjs/common';
import { Author } from 'src/lib/interface';

interface UpdateOptions {
    params?: string[];
    swagger?: {
        body?: Type<unknown>;
    };
    author?: Author;
}

DELETE

import { Author } from 'src/lib/interface';

interface DeleteOptions {
    params?: string[];
    softDelete?: boolean;
    author?: Author;
}

UPSERT

interface UpsertOptions {
    params?: string[];
    swagger?: {
        body?: Type<unknown>;
    };
    author?: Author;
}

RECOVER

interface RecoverOptions {
    params?: string[];
    author?: Author;
}

only

(optional) An array of methods to generate routes for. If not specified, all routes will be generated.

For example, if you want to generate only create and retrieve one, you can specify the following configuration.

import { Crud, Method } from '@nestjs-library/crud';

@Crud({ entity: User, only: [Method.CREATE,  Method.READ_ONE] })

Contributors

Contributors

Star History

Star History Chart

License

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