Generic CRUD Service for Angular
When we analyze Angular projects, we can find lots of duplicated code for simplest things. One piece of code that is often duplicated is the CRUD feature, it we always do. To solve this problem we can create a class to manage this feature.
To create the smallest and reusable class we can think of some points:
- Have the main CRUD methods;
- To be Extendable;
- To be Configurable;
The request pattern we want to satisfy here is:
- Use BASE_API from environment;
- Make requests to the environment.BASE_API/some-endpoint;
- BASE_API could be replaced;
- A return type could be defined;
- fetchEntities, with or without query params;
- createEntity;
- fetchEntity by Id;
- updateEntity, making a put request with updated object at the body of the request;
- deleteEntity;
This service allows us to, agnostically, make the CRUD requests and that’s all.
in order to use this we can create another service and extends it. The service will extend all these CRUD methods and properties.
I purposely set the properties as protected, just to make it reusable to create other methods and behaviors.
The CRUD Service does not have the Injectable decorator it must be extented by a service or even instantiable.
Above we have a classe extending the CRUD Service to make those requests.
We can also instantiate the CrudService class in some cases, if it is needed.
It’s a simple and reusable code with just one propose, to make CRUD requests. Aspects like properties visibility and headers you can customize for your own project.