Let's walk through a practical example of creating a service with methods and using it in a controller step by step.
Step 1: Create the UserService
First, let's create a UserService that will provide user-related functionality. In a new file, create a user.service.ts
file and define the UserService class as follows:
@Injectable()
export class UserService {
getUsers(): string[] {
// Logic to fetch users from a data source
return ['User 1', 'User 2', 'User 3'];
}
getUserById(id: number): string {
// Logic to fetch a specific user by ID from a data source
return `User with ID ${id}`;
}
addUser(user: string): void {
// Logic to add a new user to a data source
console.log(`Adding user: ${user}`);
}
}
The UserService class has three methods: getUsers()
, getUserById(id)
, and addUser(user)
. These methods simulate fetching users, retrieving a specific user by ID, and adding a new user to a data source.
Step 2: Create the UserController
Next, let's create a UserController that will handle HTTP requests related to users. In a new file, create a user.controller.ts
file and define the UserController class as follows:
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
getUsers(): string[] {
return this.userService.getUsers();
}
@Get(':id')
getUserById(@Param('id') id: number): string {
return this.userService.getUserById(id);
}
@Post()
addUser(@Body('user') user: string): void {
this.userService.addUser(user);
}
}
The UserController is marked with the @Controller('users')
decorator, specifying the base route path for the controller's endpoints as /users
.
The constructor of the UserController has a parameter of type UserService, which represents the dependency on the UserService. Nest.js will automatically create an instance of UserService and inject it into the UserController.
The UserController has three methods decorated with HTTP decorators: @Get()
, @Get(':id')
, and @Post()
. These methods handle HTTP GET and POST requests for fetching users, retrieving a user by ID, and adding a new user, respectively. Inside these methods, we delegate the functionality to the corresponding methods of the injected UserService instance.
Step 3: Provide the UserService
Finally, to make sure Nest.js is aware of the UserService as a provider, open the app.module.ts
file and add the UserService to the providers array:
@Module({
providers: [UserService],
controllers: [UserController],
})
export class AppModule {}
This tells Nest.js to create an instance of UserService whenever it is required and inject it into the UserController.
That's it! Now you have a UserService with methods for user-related functionality and a UserController that uses the UserService to handle HTTP requests related to users.
By following these steps, Nest.js will automatically handle the dependency injection for you, creating an instance of UserService and injecting it into the UserController. This allows you to call the UserService methods from within the UserController to perform user-related operations.
You can then start the Nest.js application and test the UserController's endpoints for fetching users, retrieving a user by ID, and adding a new user, which will utilize the UserService's functionality.