Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x | "use strict";
const path = require("path"),
{ isString, isFunction, noop } = require("lodash"),
Validator = require("fastest-validator"),
v = new Validator();
import { ServiceBroker } from "moleculer";
import { AppError } from "../errors";
const { isClass } = require("../utils/isClass");
import * as PrometheusService from "../mixins/metrics.prometheus.service";
const DefaultServiceStarterSchema = {
services: {
type: "array",
items: "any", //string, function, or obj
min: 1
}
};
let DefaultServiceBroker;
const DefaultInternalServices = [];
const DefaultMixins = [PrometheusService];
/**
* [CreateServiceStarter description]
* @param {[type]} _servicebroker_ [description]
* @param {[type]} _metricsreporter_ [description]
* @param {[type]} _tracer_ [description]
*/
export function CreateServiceStarter(_servicebroker_?) {
DefaultServiceBroker = _servicebroker_ || ServiceBroker; //or fallback to default
return ServiceStarter;
}
/**
* [ServiceStarter description]
* @param {[type]} services [description]
* @param {[type]} broker [description]
*
* return [Broker, loadedServices, internalServices] tuple;
*/
async function ServiceStarter(services, broker?) {
services = Array.isArray(services) ? services : [services];
//validate
let checker = v.validate(
{
services: services
},
DefaultServiceStarterSchema
);
Iif (checker !== true) {
throw new AppError(`Cannot start services, ${checker[0].message}`);
}
// Create broker
let Broker = broker || new DefaultServiceBroker(); //priorotize custom supplied broker //or use default binded broker
//load default internal services, e.g dino ...etc
let internals = loadServices(
DefaultInternalServices,
DefaultMixins,
Broker,
true
);
//load user services
let loadeds = loadServices(services, DefaultMixins, Broker, false);
await Broker.start();
//return Broker;
return [Broker, loadeds, internals];
}
/** syntax desugaring */
function loadServices(services, mixins, broker, local = false) {
return services.map(service => {
let serviceSchema = isString(service)
? require(path.resolve(local ? __dirname : process.cwd(), service)) //start('my.service.js')
: service;
Iif (!isClass(serviceSchema) && isFunction(serviceSchema)) {
serviceSchema = serviceSchema();
}
//injecting default mixins
Eif (Array.isArray(mixins)) {
serviceSchema.mixins =
serviceSchema.mixins && Array.isArray(serviceSchema.mixins)
? mixins.concat(serviceSchema.mixins)
: mixins;
}
return broker.createService(serviceSchema); //Service instance
});
}
|