Tutorial: Custom Services

Custom Services

In addition to the services provided by Flitter and its packages, you can create custom services for your application. These services are processed by the libflitter/services/ServicesUnit~ServicesUnit when the application starts, and are made available to the rest of the application.

That means that, when you create a named service, you can require it in any other injectable class like you would the built-in services (eg models/controllers/middleware).

Creating a Custom Service

You can generate a service using the ./flitter command:

./flitter new service some:Service

This will generate the file app/services/some/Service.service.js:

const { Service } = require('flitter-di')

/*
 * Service Service
 * -------------------------------------------------------------
 * This is a service file that will be made available through Flitter's
 * dependency injector to the rest of the application based on its given
 * canonical name.
 *
 * e.g. app.di().service("Service")
 */
class ServiceService extends Service {
    static get services() {
        return [...super.services, 'app', /* Additional services here (e.g. "configs", "output", &c. */]
    }
    
    // Service methods here

}

module.exports = exports = ServiceService

Services are named by their canonical name. So, you can require a service by specifying its unqualified canonical name in the static services getter for whatever injectable class you want to use it in:

// app/models/SomeModel.model.js
const { Model } = require('flitter-orm')

class SomeModel extends Model {
	static get services() {
		return [...super.services, 'some:Service'],
	}

	service_test() {
		this['some:Service'].method_on_the_service()
	}
}

These services are also accessible from the application-level dependency injector. So, you can use them in the Flitter Shell, as well:

> _services['some:Service']
ServiceService {}
> _di.get('some:Service')
ServiceService {}