Building Extendable Generic Nestjs Controller

Amro Abdalla
2 min readOct 14, 2022

--

When I was working with the Django rest framework, there was a class called ModelViewSet, just inheriting this class and specifying your database model name, all the CRUD endpoints would be created for you automatically. I really liked this idea as it gives you consistency look to your API, less code has to be written and finally lets you focus more on the business logic.

This article will provide implementation to a generic class that when it is extended will provide similar functionality to ModelViewSet.

In order to do that TypeORM library is used, as our model library. As an example, I will do the classic Article model and will show how I will do the endpoints for it, as the model would be:

Article Entity

The controller of this model with a GET endpoint would be normally like this:

Basic Article Controller

Now we have to create an abstract generic class with a GET function, I will call it EndPointSet, and it would look like this without implementation:

Generic Controller Class without Implementation yet

But now we have a problem, each different model would have a different id field name, so we can not use the findOne method, luckily Typeform provides the findOneById method, which needs only the id value, not its name, so the method implementation would be:

return this.repository.findOneById(id);

And now we can inherit the EndPointSet not only in the ArticleController but any controller as follows:

the other endpoints will be similar to what we did in the Get function, so the final class at the end would be like that:

EndPointSet Class

So yeah that is it, we now made our generic controller with all the CRUD endpoints. That is it for the first part, in the next part, I will do more work on the list function, in order to do pagination, ordering, filter.. etc. So follow for more ^^.

--

--