Services
An overview of services and how to use them
Introduction
Services are software entities that operate in the background of the application, and outside of the controllers, routers, and listeners. Services are singletons as well—meaning only one instance of the service exists at all times.
Examples of services include:
Connection manager for MongoDB
Local caching algorithm for a content delivery network (CDN)
Gateway for communicating with Firebase Cloud Messaging
All services are located in app/services
.
Implementing a Service
You implement a service by extending the Service
class. Here is an example service for storing the messages we originally stored in a controller.
As shown in the example implementation above, the service has methods for adding and finding messages.
Accessing a Service
You access a service by defining a property with the value service([name])
. This method will bind the service to the associated property.
The name parameter is require if the (file) name of the service does not match the name of the property. For example, if a service is in a file named local-cache
, then you must use service('local-cache')
to access the service.
Below, we have re-implemented the message controller to use the message service.
In the example above, you will notice that the messages
property has been changed from an array to a reference to the messages
service. Now, the controller will read and write message to and from the messages
service. More importantly, other entities can access this service and manipulate to the same messages this controller is able to manipulate.
Service Lifecycle
Services are loaded automatically by the application after the application has loaded its configuration files. Once the service is loaded into member, its lifecycle methods are called in the following order:
configure
This method is called when the service is to configure itself. Theconfigure()
method should not be confused with theinit()
method. Theinit()
method is for synchronous configuration whereas theconfigure()
method is for asynchronous configuration. This is because the configure method can return aPromise
to signify asynchronous configuration.start
This method is called when the service is started. If the service must perform any asynchronous operations, then it can return aPromise
.destroy
This method is called when the service is being destroyed. If the service must perform any asynchronous operations, then it can return aPromise
.
Last updated