Services
A service in Blueprint is a software component that operate in the background of the application, and outside of the controllers, routers, and listeners. Services can also be references by other software components, including services themselves. For example, you could recreate a service that performs periodic background tasks, or a service that manages connections to a database.
In our example, we want to migrate the data stored in the rental controller to a service. This will allow different software entities in the Blueprint application, such as another controller, to reference the same data as the rental controller.
Defining the Service
First, lets generate the service using the Blueprint cli.
This command will generate an empty service.
The service is automatically loaded by the Blueprint application when started.
Implementing the Service
For the service, we need a method for adding rentals, deleting rentals, getting all the rentals, and getting a single rental. We are also going to initialize the service with the original data.
Using the Service
Let's go back to our rental
controller and re-implement the rental.get
using the rentals
service from above. To load a service into the rental
controller, just use the service
computed property.
Let's break down the example above since we have made some changes to the original controller code. First, we load the service into the controller using the service()
computed property function, which is available via the rentals
property on the controller. Next, we updated the get()
action implementation to retrieve the rental data from the service.
All actions can access to the parent controller using thethis.controller
property.
Now, when you restart the application and open the browser to http://localhost:5000/api/rentals, you will get the same response as before. The only difference this time is the data is pulled from the rentals
service, and not from local data in the controller.