Reusing logic with Strapi services
Services are utility functions that are mostly used by controllers to perform different operations. Their typical use is to access the database, but they can encapsulate any other logic – such as sending emails or integrating with other systems – that we want to share with other components of a Strapi API. Conceptually, they keep our logic DRY (which stands for don't repeat yourself) by encapsulating these reusable operations.
Similar to controllers, if we have a look at the service file that Strapi generated for us (for example, services/classroom.js
), we will find that it's empty. This is because, similar to the routes and the controller, Strapi provides a default Core
service that we can customize or extend in this file if we want to (the same concept as the default Core
controller in the previous section) using the createCoreService
factory method.
Let's customize the classroom service by adding a new method...