104. Services
Services
- Providers | NestJS - A progressive Node.js framework
- Services are a specific type of provider in Nest.js that encapsulate reusable business logic(i.e CRUD, Billing…).
- They are typically used to abstract complex operations and promote code reuse across different parts of the application.
- Services help maintain a modular architecture and can be easily injected into controllers or other services as a singleton.
nest g s service-name
@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
create(cat: Cat) {
this.cats.push(cat);
}
findAll(): Cat[] {
return this.cats;
}
}
@Controller('cats')
export class CatsController {
constructor(private catsService: CatsService) {}
@Post()
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
@Get()
async findAll(): Promise<Cat[]> {
return this.catsService.findAll();
}
}
- Finally you need to add your service to respective module
@Module({
controllers: [CatsController],
providers: [CatsService],
})
export class AppModule {}
There are different type of providers in addition to services, to learn more check Providers