Search code examples
nestjssequelize-typescript

Can I do DB-related work in the controller right away without going through the service in nestjs?


I'm developing it using nestjs, sequelize, but when I write DB-related logic in the service, there is only one line of method, so I'm trying to work directly on the controller, is there a problem?

export class UserController{
    constructor(
        @InjectModel(User)
        private readonly userRepo: User,
    )

    async createUser(@Body createData: CreateUserDto){
        return this.userRepo.create(createData);
    }
}

Solution

  • You can, yes. The idea behind using a service is to abstract the logic away from the HTTP handler, so that if you end up needing other approaches (CLI, RPC, Websockets, GraphQL, Bots, etc) you can re-use the service without having to re-create the logic that otherwise lives in the controller. But if you're 100% certain you'll never need that level of abstraction, and never want to have to deal with it, then sure, you can do it all in the controller.