Nest CRUD controllers and services
@nestjsx/crud
has been designed for creating CRUD controllers and services in Nest applications. It can be used with TypeORM repositories for now, but Mongoose and additional functionality will be available soon.
API Methods and Endpoints
Assume you've created some CRUD controller with the route @Controller('cats')
. In that case, Nest will create endpoints as follows:
GET /cats
Res Data: array of entities; an empty array
Res Code: 200
GET /cats/:id
Req Params: :id
- entity id
Res Data: entity object
Res Code: 200; 400; 404
POST /cats
Req Body: entity object
Res Data: entity object
Res Code: 201; 400
PUT /cats/:id
Req Params: :id
- entity id
Req Body: entity object
Res Data: entity object
Res Code: 201; 400; 404
DELETE /cats/:id
Req Params: :id
- entity id
Res Data: empty
Res Code: 200; 400; 404
Using with TypeORM
1. Install
npm i @nestjsx/crud typeorm @nestjs/typeorm --save
2. Create TypeORM Entity
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class Cat {
@PrimaryGeneratedColumn() id: number;
@Column() name: string;
}
3. Create Service
import { CrudTypeOrmService } from '@nestjsx/crud/typeorm';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cat } from './cat.entity';
@Injectable()
export class CatsCrudService extends CrudTypeOrmService<Cat> {
constructor(
@InjectRepository(Cat) private readonly repository: Repository<Cat>,
) {
super(repository);
}
}
4. Create Controller
import { CrudController } from '@nestjsx/crud';
import { Controller } from '@nestjs/common';
import { Cat } from './cat.entity';
import { CatsCrudService } from './cats-crud.service';
@Controller('cats')
export class CatsCrudController extends CrudController<Cat> {
constructor(private readonly catsCrudService: CatsCrudService) {
super(catsCrudService);
}
}
5. Connect everything in your Module
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cat } from './cat.entity';
import { CatsCrudService } from './cats-crud.service';
import { CatsCrudController } from './cats-crud.controller';
@Module({
imports: [TypeOrmModule.forFeature([Cat])],
providers: [CatsCrudService],
controllers: [CatsCrudController],
})
export class CatsModule {}
Tests
npm run test
npm run test:e2e
Roadmap
- CRUD for TypeORM
- CRUD for Mongoose
- Expose as Dynamic Module
- Swagger integration
- Working with relations (extending CRUD)
Thanks
This was inspired by nestjs-generic-crud
License
MIT