Services

Services contain the business logic of your application. They are registered in the DI container and injected into controllers or other services.

Creating a Service

A service is just a plain TypeScript class. Nova's DI system takes care of making it injectable:

user.service.ts TypeScript
export class UserService {
  private users = [
    { id: 1, name: 'Alice', email: 'alice@mail.com' },
    { id: 2, name: 'Bob', email: 'bob@mail.com' },
  ];

  findAll() {
    return this.users;
  }

  findById(id: number) {
    return this.users.find(u => u.id === id);
  }

  create(data: { name: string; email: string }) {
    const user = { id: this.users.length + 1, ...data };
    this.users.push(user);
    return user;
  }
}

Registering the Service

user.module.ts TypeScript
import { Module } from '@abrahambass/nova';
import { UserController } from './user.controller';
import { UserService } from './user.service';

export const UserModule = new Module()
  .registerController(UserController)
  .registerSingleton(UserService);

Injecting into a Controller

user.controller.ts TypeScript
import { Controller, Get, Post, Body, Path, inject } from '@abrahambass/nova';
import { UserService } from './user.service';
import { CreateUserSchema } from './dto/create-user';

@Controller('/users')
class UserController {
  constructor(
    @inject(UserService) private userService: UserService,
  ) {}

  @Get()
  async findAll() {
    return this.userService.findAll();
  }

  @Get('/:id')
  async findById(@Path('id') id: number) {
    return this.userService.findById(id);
  }

  @Post()
  async create(@Body(CreateUserSchema) data) {
    return this.userService.create(data);
  }
}