Сущность Сервис представляет микросервис в фреймворке Moleculer. У сервисов описываются действия (actions) и возможно подписаться на события. Для создания сервиса необходимо описать его схему. Схема сервиса похожа на компонент из VueJS.
Схема сервиса
У схемы есть некоторые свойства: name, version, settings, actions, methods, events.
Простой пример схемы сервиса с двумя действиями
| // math.service.js | 
Базовые свойства
В схеме у каждого сервиса должны быть указаны базовые свойства.
| // posts.v1.service.js | 
name является обязательным свойством и оно должно быть установлено. It’s the first part of action name when you call it.
To disable service name prefixing set
$noServiceNamePrefix: truein Service settings.
The version is an optional property. Use it to run multiple version from the same service. It is a prefix in the action name. It can be a Number or a String.
| // posts.v2.service.js | 
To call this find action on version 2 service:
| broker.call("v2.posts.find"); | 
REST callVia API Gateway, make a request to
GET /v2/posts/find.
To disable version prefixing set
$noVersionPrefix: truein Service settings.
Настройки
The settings property is a static store, where you can store every settings/options to your service. You can reach it via this.settings inside the service.
| // mailer.service.js | 
The
settingsis also obtainable on remote nodes. It is transferred during service discovering.
Internal Settings
There are some internal settings which are used by core modules. These setting names start with $ (dollar sign).
| Название | Тип | Значение по умолчанию | Описание | 
|---|---|---|---|
| $noVersionPrefix | Boolean | false | Disable version prefixing in action names. | 
| $noServiceNamePrefix | Boolean | false | Disable service name prefixing in action names. | 
| $dependencyTimeout | Number | 0 | Timeout for dependency waiting. | 
| $shutdownTimeout | Number | 0 | Timeout for waiting for active requests at shutdown. | 
| $secureSettings | Array | [] | List of secure settings. | 
Secure service settings
To protect your tokens & API keys, define a $secureSettings: [] property in service settings and set the protected property keys. The protected settings won’t be published to other nodes and it won’t appear in Service Registry. These settings will only available under this.settings inside the service functions.
| // mail.service.js | 
Mixins
Mixins are a flexible way to distribute reusable functionalities for Moleculer services. The Service constructor merges these mixins with the current schema. When a service uses mixins, all properties present in the mixin will be “mixed” into the current service.
Example how to extend moleculer-web service
| // api.service.js | 
The above example creates an api service which inherits all properties from ApiGwService but overwrite the port setting and extend it with a new myAction action.
Merge algorithm
The merge algorithm depends on the property type.
| Property | Algorithm | 
|---|---|
| name,version | Merge & overwrite. | 
| settings | Deep extend with defaultsDeep. | 
| metadata | Deep extend with defaultsDeep. | 
| actions | Deep extend with defaultsDeep. You can disable an action from mixin if you set to falsein your service. | 
| hooks | Deep extend with defaultsDeep. | 
| methods | Merge & overwrite. | 
| events | Concatenate listeners. | 
| created,started,stopped | Concatenate listeners. | 
| mixins | Merge & overwrite. | 
| dependencies | Merge & overwrite. | 
| any custom | Merge & overwrite. | 
Merge algorithm examplesMerge & overwrite: if serviceA has
a: 5,b: 8and serviceB hasc: 10,b: 15, the mixed service will havea: 5,b: 15andc: 10. Concatenate: if serviceA & serviceB subscribe tousers.createdevent, both event handler will be called when theusers.createdevent emitted.
Действия
Действия (Action) это публично вызываемый метод сервиса. They are callable with broker.call or ctx.call. The action could be a Function (shorthand for handler) or an object with some properties and handler. The actions should be placed under the actions key in the schema. For more information check the actions documentation.
| // math.service.js | 
You can call the above actions as
| const res = await broker.call("math.add", { a: 5, b: 7 }); | 
Inside actions, you can call other nested actions in other services with ctx.call method. It is an alias to broker.call, but it sets itself as parent context (due to correct tracing chains).
| // posts.service.js | 
In action handlers the
thisis always pointed to the Service instance.
События
You can subscribe to events under the events key. For more information check the events documentation.
| // report.service.js | 
In event handlers the
thisis always pointed to the Service instance.
Grouping
The broker groups the event listeners by group name. By default, the group name is the service name. But you can overwrite it in the event definition.
| // payment.service.js | 
Methods
To create private methods in the service, put your functions under the methods key. These functions are private, can’t be called with broker.call. But you can call it inside service (from action handlers, event handlers and lifecycle event handlers).
Первые шаги
| // mailer.service.js | 
If you want to wrap a method with a middleware use the following notation:
| // posts.service.js | 
The method name can’t be
name,version,settings,metadata,schema,broker,actions,logger, because these words are reserved in the schema.
In methods the
thisis always pointed to the Service instance.
Lifecycle Events
There are some lifecycle service events, that will be triggered by broker. They are placed in the root of schema.
| // www.service.js | 
Dependencies
If your service depends on other services, use the dependencies property in the schema. The service waits for dependent services before calls the started lifecycle event handler.
| // posts.service.js | 
The started service handler is called once the likes, v2.auth, v2.users, staging.comments services are available (either the local or remote nodes).
Wait for services via ServiceBroker
To wait for services, you can also use the waitForServices method of ServiceBroker. It returns a Promise which will be resolved, when all defined services are available & started.
Параметры
| Parameter | Тип | Значение по умолчанию | Описание | 
|---|---|---|---|
| services | StringorArray | - | Service list to waiting | 
| timeout | Number | 0 | Waiting timeout. 0means no timeout. If reached, aMoleculerServerErrorwill be rejected. | 
| interval | Number | 1000 | Frequency of watches in milliseconds | 
Пример
| broker.waitForServices(["posts", "v2.users"]).then(() => { | 
Set timeout & interval
| broker.waitForServices("accounts", 10 * 1000, 500).then(() => { | 
Метаданные
The Service schema has a metadata property. You can store here any meta information about service. You can access it as this.metadata inside service functions. Moleculer core modules don’t use it. You can store in it whatever you want.
| module.exports = { | 
The
metadatais also obtainable on remote nodes. It is transferred during service discovering.
Properties of Service Instances
In service functions, this is always pointed to the Service instance. It has some properties & methods what you can use in your service functions.
| Название | Тип | Описание | 
|---|---|---|
| this.name | String | Name of service (from schema) | 
| this.version | NumberorString | Version of service (from schema) | 
| this.fullName | String | Name of version prefix | 
| this.settings | Object | Settings of service (from schema) | 
| this.metadata | Object | Metadata of service (from schema) | 
| this.schema | Object | Schema definition of service | 
| this.broker | ServiceBroker | Instance of broker | 
| this.Promise | Promise | Class of Promise (Bluebird) | 
| this.logger | Логгер | Logger instance | 
| this.actions | Object | Actions of service. Service can call own actions directly | 
| this.waitForServices | Function | Link to broker.waitForServicesmethod | 
| this.currentContext | Контекст | Get or set the current Context object. | 
Service Creation
There are several ways to create and load a service.
broker.createService()
For testing, developing or prototyping, use the broker.createService method to load & create a service by schema. It’s simplest & fastest.
| broker.createService({ | 
Load service from file
The recommended way is to place your service code into a single file and load it with the broker.
math.service.js
| // Export the schema of service | 
Load it with broker:
| // Create broker | 
In the service file you can also create the Service instance. In this case, you have to export a function which returns the instance of Service.
| const { Service } = require("moleculer"); | 
Or create a function which returns with the schema of service
| // Export a function, the `loadService` will call with the ServiceBroker instance. | 
Load multiple services from a folder
If you have many services (and you will have) we suggest to put them to a services folder and load all of them with the broker.loadServices method.
Синтаксис
| broker.loadServices(folder = "./services", fileMask = "**/*.service.js"); | 
Пример
| // Load every *.service.js file from the "./services" folder (including subfolders) | 
Load with Moleculer Runner (recommended)
We recommend to use the Moleculer Runner to start a ServiceBroker and load services. Подробнее о Moleculer Runner. It is the easiest way to start a node.
Hot Reloading Services
Moleculer has a built-in hot-reloading function. During development, it can be very useful because it reloads your services when you modify it. You can enable it in broker options or in Moleculer Runner. Demo video how it works.
Enable in broker options
| const broker = new ServiceBroker({ | 
Enable it in Moleculer Runner
Turn it on with --hot or -H flags.
| $ moleculer-runner --hot ./services/test.service.js | 
Hot reloading function is working only with Moleculer Runner or if you load your services with
broker.loadServiceorbroker.loadServices. It doesn’t work withbroker.createService.
Hot reload mechanism watches the service files and their dependencies. Every time a file change is detected the hot-reload mechanism will track the services that depend on it and will restart them.
Local Variables
If you would like to use local properties/variables in your service, declare them in the created event handler.
Example for local variables
| const http = require("http"); | 
Naming restrictionIt is important to be aware that you can’t use variable name which is reserved for service or coincides with your method names! E.g.
this.name,this.version,this.settings,this.schema…etc.
ES6 Classes
If you prefer ES6 classes to Moleculer service schema, you can write your services in ES6 classes. There are two ways to do it.
Native ES6 classes with schema parsing
Define actions and events handlers as class methods and call the parseServiceSchema method in constructor with schema definition where the handlers pointed to these class methods.
| const Service = require("moleculer").Service; | 
Use decorators
Thanks for @ColonelBundy, you can use ES7/TS decorators as well: moleculer-decorators
Need a compilerPlease note, you must use Typescript or Babel to compile decorators.
Example service
| const { ServiceBroker } = require('moleculer'); | 
Internal Services
The ServiceBroker contains some internal services to check the node health or get some registry information. You can disable them by setting internalServices: false in broker options.
List of nodes
It lists all known nodes (including local node).
| broker.call("$node.list").then(res => console.log(res)); | 
Параметры
| Название | Тип | Значение по умолчанию | Описание | 
|---|---|---|---|
| withServices | Boolean | false | List with services. | 
| onlyAvailable | Boolean | false | List only available nodes. | 
List of services
It lists all registered services (local & remote).
| broker.call("$node.services").then(res => console.log(res)); | 
Параметры
| Название | Тип | Значение по умолчанию | Описание | 
|---|---|---|---|
| onlyLocal | Boolean | false | List only local services. | 
| skipInternal | Boolean | false | Skip the internal services ( $node). | 
| withActions | Boolean | false | List with actions. | 
| onlyAvailable | Boolean | false | List only available services. | 
List of local actions
It lists all registered actions (local & remote).
| broker.call("$node.actions").then(res => console.log(res)); | 
It has some options which you can declare within params.
Параметры
| Название | Тип | Значение по умолчанию | Описание | 
|---|---|---|---|
| onlyLocal | Boolean | false | List only local actions. | 
| skipInternal | Boolean | false | Skip the internal actions ( $node). | 
| withEndpoints | Boolean | false | List with endpoints (nodes). | 
| onlyAvailable | Boolean | false | List only available actions. | 
List of local events
It lists all event subscriptions.
| broker.call("$node.events").then(res => console.log(res)); | 
It has some options which you can declare within params.
Параметры
| Название | Тип | Значение по умолчанию | Описание | 
|---|---|---|---|
| onlyLocal | Boolean | false | List only local subscriptions. | 
| skipInternal | Boolean | false | Skip the internal event subscriptions $. | 
| withEndpoints | Boolean | false | List with endpoints (nodes). | 
| onlyAvailable | Boolean | false | List only available subscriptions. | 
List of metrics
It lists all metrics.
| broker.call("$node.metrics").then(res => console.log(res)); | 
It has some options which you can declare within params.
Параметры
| Название | Тип | Значение по умолчанию | Описание | 
|---|---|---|---|
| types | StringorArray | null | Type of metrics to include in response. | 
| includes | StringorArray | null | List of metrics to be included in response. | 
| excludes | StringorArray | null | List of metrics to be excluded from the response. | 
Get Broker options
It returns the broker options.
| broker.call("$node.options").then(res => console.log(res)); | 
Health of node
It returns the health info of local node (including process & OS information).
| broker.call("$node.health").then(res => console.log(res)); | 
Example health info:
| { | 
Please note, internal service actions are not traced.
Extending
Internal service can be easily extended with custom functionalities. To do it you must define a mixin schema in broker´s internalServices option.
| // moleculer.config.js |