knifecycle
Advanced tools
Comparing version 3.1.0 to 4.0.0
@@ -0,1 +1,21 @@ | ||
# [4.0.0](https://github.com/nfroidure/knifecycle/compare/v3.1.0...v4.0.0) (2018-11-04) | ||
### chore | ||
* **Dependencies:** Update `metapak-nfroidure` ([dc65134](https://github.com/nfroidure/knifecycle/commit/dc65134)) | ||
### Features | ||
* **autoInject:** Adds a utility function to autodetect dependencies ([03c8527](https://github.com/nfroidure/knifecycle/commit/03c8527)) | ||
* **autoName:** Allow to set name according to the function name ([19cde56](https://github.com/nfroidure/knifecycle/commit/19cde56)) | ||
### BREAKING CHANGES | ||
* **Dependencies:** Drop support for NodeJS < 8 versions | ||
<a name="3.1.0"></a> | ||
@@ -2,0 +22,0 @@ # [3.1.0](https://github.com/nfroidure/knifecycle/compare/v3.0.0...v3.1.0) (2018-10-14) |
@@ -12,6 +12,2 @@ "use strict"; | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
/* Architecture Note #2: Build | ||
@@ -57,54 +53,44 @@ | ||
function initInitializerBuilder(_x) { | ||
return _initInitializerBuilder.apply(this, arguments); | ||
} | ||
async function initInitializerBuilder({ | ||
$autoload | ||
}) { | ||
return buildInitializer; | ||
/** | ||
* Create a JavaScript module that initialize | ||
* a set of dependencies with hardcoded | ||
* import/awaits. | ||
* @param {String[]} dependencies | ||
* The main dependencies | ||
* @return {Promise<String>} | ||
* The JavaScript module content | ||
* @example | ||
* import initInitializerBuilder from 'knifecycle/dist/build'; | ||
* | ||
* const buildInitializer = await initInitializerBuilder({ | ||
* $autoload: async () => {}, | ||
* }); | ||
* | ||
* const content = await buildInitializer(['entryPoint']); | ||
*/ | ||
function _initInitializerBuilder() { | ||
_initInitializerBuilder = _asyncToGenerator(function* ({ | ||
$autoload | ||
}) { | ||
return buildInitializer; | ||
/** | ||
* Create a JavaScript module that initialize | ||
* a set of dependencies with hardcoded | ||
* import/awaits. | ||
* @param {String[]} dependencies | ||
* The main dependencies | ||
* @return {Promise<String>} | ||
* The JavaScript module content | ||
* @example | ||
* import initInitializerBuilder from 'knifecycle/dist/build'; | ||
* | ||
* const buildInitializer = await initInitializerBuilder({ | ||
* $autoload: async () => {}, | ||
* }); | ||
* | ||
* const content = await buildInitializer(['entryPoint']); | ||
*/ | ||
function buildInitializer(_x4) { | ||
return _buildInitializer.apply(this, arguments); | ||
} | ||
function _buildInitializer() { | ||
_buildInitializer = _asyncToGenerator(function* (dependencies) { | ||
const dependencyTrees = yield Promise.all(dependencies.map(dependency => buildDependencyTree({ | ||
$autoload | ||
}, dependency))); | ||
const dependenciesHash = buildDependenciesHash(dependencyTrees.filter(identity)); | ||
const batches = (0, _sequence.buildInitializationSequence)({ | ||
__name: 'main', | ||
__childNodes: dependencyTrees.filter(identity) | ||
}); | ||
batches.pop(); | ||
return `${batches.map((batch, index) => ` | ||
async function buildInitializer(dependencies) { | ||
const dependencyTrees = await Promise.all(dependencies.map(dependency => buildDependencyTree({ | ||
$autoload | ||
}, dependency))); | ||
const dependenciesHash = buildDependenciesHash(dependencyTrees.filter(identity)); | ||
const batches = (0, _sequence.buildInitializationSequence)({ | ||
__name: 'main', | ||
__childNodes: dependencyTrees.filter(identity) | ||
}); | ||
batches.pop(); | ||
return `${batches.map((batch, index) => ` | ||
// Definition batch #${index}${batch.map(name => { | ||
if ('constant' === dependenciesHash[name].__initializer[_util.SPECIAL_PROPS.TYPE]) { | ||
return ` | ||
if ('constant' === dependenciesHash[name].__initializer[_util.SPECIAL_PROPS.TYPE]) { | ||
return ` | ||
const ${name} = ${JSON.stringify(dependenciesHash[name].__initializer[_util.SPECIAL_PROPS.VALUE], null, 2)};`; | ||
} | ||
} | ||
return ` | ||
return ` | ||
import ${dependenciesHash[name].__initializerName} from '${dependenciesHash[name].__path}';`; | ||
}).join('')}`).join('\n')} | ||
}).join('')}`).join('\n')} | ||
@@ -114,15 +100,15 @@ export async function initialize(services = {}) {${batches.map((batch, index) => ` | ||
const batch${index} = {${batch.map(name => { | ||
if ('constant' === dependenciesHash[name].__initializer[_util.SPECIAL_PROPS.TYPE]) { | ||
return ` | ||
if ('constant' === dependenciesHash[name].__initializer[_util.SPECIAL_PROPS.TYPE]) { | ||
return ` | ||
${name}: Promise.resolve(${name}),`; | ||
} | ||
} | ||
return ` | ||
return ` | ||
${name}: ${dependenciesHash[name].__initializerName}({${dependenciesHash[name].__inject ? `${dependenciesHash[name].__inject.map(_util.parseDependencyDeclaration).map(({ | ||
serviceName, | ||
mappedName | ||
}) => ` | ||
serviceName, | ||
mappedName | ||
}) => ` | ||
${serviceName}: services['${mappedName}'],`).join('')}` : ''} | ||
})${'provider' === dependenciesHash[name].__type ? '.then(provider => provider.service)' : ''},`; | ||
}).join('')} | ||
}).join('')} | ||
}; | ||
@@ -135,10 +121,10 @@ | ||
${batch.map(name => { | ||
return ` | ||
return ` | ||
services['${name}'] = await batch${index}['${name}'];`; | ||
}).join('')} | ||
}).join('')} | ||
`).join('')} | ||
return {${dependencies.map(_util.parseDependencyDeclaration).map(({ | ||
serviceName, | ||
mappedName | ||
}) => ` | ||
serviceName, | ||
mappedName | ||
}) => ` | ||
${serviceName}: services['${mappedName}'],`).join('')} | ||
@@ -148,55 +134,44 @@ }; | ||
`; | ||
}); | ||
return _buildInitializer.apply(this, arguments); | ||
} | ||
}); | ||
return _initInitializerBuilder.apply(this, arguments); | ||
} | ||
} | ||
function buildDependencyTree(_x2, _x3) { | ||
return _buildDependencyTree.apply(this, arguments); | ||
} | ||
async function buildDependencyTree({ | ||
$autoload | ||
}, dependencyDeclaration) { | ||
const { | ||
mappedName, | ||
optional | ||
} = (0, _util.parseDependencyDeclaration)(dependencyDeclaration); | ||
function _buildDependencyTree() { | ||
_buildDependencyTree = _asyncToGenerator(function* ({ | ||
$autoload | ||
}, dependencyDeclaration) { | ||
try { | ||
const { | ||
mappedName, | ||
optional | ||
} = (0, _util.parseDependencyDeclaration)(dependencyDeclaration); | ||
path, | ||
initializer | ||
} = await $autoload(mappedName); | ||
const node = { | ||
__name: mappedName, | ||
__initializer: initializer, | ||
__inject: initializer && initializer[_util.SPECIAL_PROPS.INJECT] ? initializer[_util.SPECIAL_PROPS.INJECT] : [], | ||
__type: initializer && initializer[_util.SPECIAL_PROPS.TYPE] ? initializer[_util.SPECIAL_PROPS.TYPE] : 'provider', | ||
__initializerName: 'init' + upperCaseFirst(mappedName), | ||
__path: path, | ||
__childNodes: [] | ||
}; | ||
try { | ||
const { | ||
path, | ||
initializer | ||
} = yield $autoload(mappedName); | ||
const node = { | ||
__name: mappedName, | ||
__initializer: initializer, | ||
__inject: initializer && initializer[_util.SPECIAL_PROPS.INJECT] ? initializer[_util.SPECIAL_PROPS.INJECT] : [], | ||
__type: initializer && initializer[_util.SPECIAL_PROPS.TYPE] ? initializer[_util.SPECIAL_PROPS.TYPE] : 'provider', | ||
__initializerName: 'init' + upperCaseFirst(mappedName), | ||
__path: path, | ||
__childNodes: [] | ||
}; | ||
if (initializer[_util.SPECIAL_PROPS.INJECT] && initializer[_util.SPECIAL_PROPS.INJECT].length) { | ||
const childNodes = await Promise.all(initializer[_util.SPECIAL_PROPS.INJECT].map(childDependencyDeclaration => buildDependencyTree({ | ||
$autoload | ||
}, childDependencyDeclaration))); | ||
node.__childNodes = childNodes.filter(identity); | ||
return node; | ||
} else { | ||
return node; | ||
} | ||
} catch (err) { | ||
if (optional) { | ||
return null; | ||
} | ||
if (initializer[_util.SPECIAL_PROPS.INJECT] && initializer[_util.SPECIAL_PROPS.INJECT].length) { | ||
const childNodes = yield Promise.all(initializer[_util.SPECIAL_PROPS.INJECT].map(childDependencyDeclaration => buildDependencyTree({ | ||
$autoload | ||
}, childDependencyDeclaration))); | ||
node.__childNodes = childNodes.filter(identity); | ||
return node; | ||
} else { | ||
return node; | ||
} | ||
} catch (err) { | ||
if (optional) { | ||
return null; | ||
} | ||
throw err; | ||
} | ||
}); | ||
return _buildDependencyTree.apply(this, arguments); | ||
throw err; | ||
} | ||
} | ||
@@ -203,0 +178,0 @@ |
@@ -15,16 +15,5 @@ "use strict"; | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
describe('buildInitializer', () => { | ||
function aProvider() { | ||
return _aProvider.apply(this, arguments); | ||
} | ||
async function aProvider() {} | ||
function _aProvider() { | ||
_aProvider = _asyncToGenerator(function* () {}); | ||
return _aProvider.apply(this, arguments); | ||
} | ||
const mockedDepsHash = { | ||
@@ -58,24 +47,11 @@ NODE_ENV: (0, _.constant)('NODE_ENV', 'development'), | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _$autoload = _asyncToGenerator(function* (name) { | ||
return mockedDepsHash[name] ? Promise.resolve({ | ||
path: `./services/${name}`, | ||
initializer: mockedDepsHash[name] | ||
}) : Promise.reject(new _yerror.default('E_UNMATCHED_DEPENDENCY', name)); | ||
}); | ||
return function $autoload(_x) { | ||
return _$autoload.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
})); | ||
it('should build an initialization module', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}, async () => { | ||
return async function $autoload(name) { | ||
return mockedDepsHash[name] ? Promise.resolve({ | ||
path: `./services/${name}`, | ||
initializer: mockedDepsHash[name] | ||
}) : Promise.reject(new _yerror.default('E_UNMATCHED_DEPENDENCY', name)); | ||
}; | ||
}); | ||
it('should build an initialization module', async () => { | ||
const $ = new _.default(); | ||
@@ -87,4 +63,4 @@ $.register((0, _.constant)('PWD', '~/my-project')); | ||
buildInitializer | ||
} = yield $.run(['buildInitializer']); | ||
const content = yield buildInitializer(['dep1', 'finalMappedDep>dep3']); | ||
} = await $.run(['buildInitializer']); | ||
const content = await buildInitializer(['dep1', 'finalMappedDep>dep3']); | ||
@@ -155,3 +131,3 @@ _assert.default.equal(content, ` | ||
`); | ||
})); | ||
}); | ||
}); |
@@ -30,2 +30,8 @@ "use strict"; | ||
}); | ||
Object.defineProperty(exports, "autoName", { | ||
enumerable: true, | ||
get: function () { | ||
return _util.autoName; | ||
} | ||
}); | ||
Object.defineProperty(exports, "inject", { | ||
@@ -37,2 +43,8 @@ enumerable: true, | ||
}); | ||
Object.defineProperty(exports, "autoInject", { | ||
enumerable: true, | ||
get: function () { | ||
return _util.autoInject; | ||
} | ||
}); | ||
Object.defineProperty(exports, "alsoInject", { | ||
@@ -114,6 +126,3 @@ enumerable: true, | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
/* eslint max-len: ["warn", { "ignoreComments": true }] */ | ||
const debug = (0, _debug.default)('knifecycle'); | ||
@@ -184,4 +193,2 @@ const DISPOSE = '$dispose'; | ||
constructor() { | ||
var _this2 = this; | ||
this._silosCounter = 0; | ||
@@ -199,19 +206,9 @@ this._silosContexts = new Set(); | ||
inject: [SILO_CONTEXT] | ||
}, | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator(function* ({ | ||
$siloContext | ||
}) { | ||
return { | ||
service: dependenciesDeclarations => _this2._initializeDependencies($siloContext, $siloContext.name, dependenciesDeclarations, { | ||
injectOnly: true | ||
}) | ||
}; | ||
}); | ||
return function (_x) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}())); | ||
}, async ({ | ||
$siloContext | ||
}) => ({ | ||
service: dependenciesDeclarations => this._initializeDependencies($siloContext, $siloContext.name, dependenciesDeclarations, { | ||
injectOnly: true | ||
}) | ||
}))); | ||
this.register((0, _util.initializer)({ | ||
@@ -224,15 +221,11 @@ name: DESTROY, | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return { | ||
service: () => { | ||
_this2.shutdownPromise = _this2.shutdownPromise || Promise.all([..._this2._silosContexts].map(siloContext => { | ||
const $dispose = siloContext.servicesDescriptors.get(DISPOSE).service; | ||
return $dispose(); | ||
})); | ||
debug('Shutting down Knifecycle instance.'); | ||
return _this2.shutdownPromise; | ||
} | ||
}; | ||
}, async () => ({ | ||
service: () => { | ||
this.shutdownPromise = this.shutdownPromise || Promise.all([...this._silosContexts].map(siloContext => { | ||
const $dispose = siloContext.servicesDescriptors.get(DISPOSE).service; | ||
return $dispose(); | ||
})); | ||
debug('Shutting down Knifecycle instance.'); | ||
return this.shutdownPromise; | ||
} | ||
}))); | ||
@@ -389,3 +382,3 @@ } | ||
* | ||
* import { Knifecycle, inject, constant, service } from 'knifecycle'; | ||
* import Knifecycle, { inject, constant, service } from 'knifecycle'; | ||
* import appInitializer from './app'; | ||
@@ -458,3 +451,3 @@ * | ||
* | ||
* import Knifecycle from 'knifecycle' | ||
* import Knifecycle, { constant } from 'knifecycle' | ||
* | ||
@@ -471,132 +464,108 @@ * const $ = new Knifecycle(); | ||
run(dependenciesDeclarations) { | ||
var _this3 = this; | ||
async run(dependenciesDeclarations) { | ||
const _this = this; | ||
return _asyncToGenerator(function* () { | ||
const _this = _this3; | ||
const internalDependencies = [...new Set(dependenciesDeclarations.concat(DISPOSE))]; | ||
const siloContext = { | ||
name: `silo-${_this3._silosCounter++}`, | ||
servicesDescriptors: new Map(), | ||
servicesSequence: [], | ||
servicesShutdownsPromises: new Map(), | ||
errorsPromises: [] | ||
}; | ||
const internalDependencies = [...new Set(dependenciesDeclarations.concat(DISPOSE))]; | ||
const siloContext = { | ||
name: `silo-${this._silosCounter++}`, | ||
servicesDescriptors: new Map(), | ||
servicesSequence: [], | ||
servicesShutdownsPromises: new Map(), | ||
errorsPromises: [] | ||
}; | ||
if (_this3.shutdownPromise) { | ||
throw new _yerror.default(E_INSTANCE_DESTROYED); | ||
} // Create a provider for the special fatal error service | ||
if (this.shutdownPromise) { | ||
throw new _yerror.default(E_INSTANCE_DESTROYED); | ||
} // Create a provider for the special fatal error service | ||
siloContext.servicesDescriptors.set(FATAL_ERROR, { | ||
service: { | ||
promise: new Promise((resolve, reject) => { | ||
siloContext.throwFatalError = err => { | ||
debug('Handled a fatal error', err); | ||
reject(err); | ||
}; | ||
}) | ||
} | ||
}); // Make the siloContext available for internal injections | ||
siloContext.servicesDescriptors.set(FATAL_ERROR, { | ||
service: { | ||
promise: new Promise((resolve, reject) => { | ||
siloContext.throwFatalError = err => { | ||
debug('Handled a fatal error', err); | ||
reject(err); | ||
}; | ||
}) | ||
} | ||
}); // Make the siloContext available for internal injections | ||
siloContext.servicesDescriptors.set(SILO_CONTEXT, { | ||
service: siloContext | ||
}); // Create a provider for the shutdown special dependency | ||
siloContext.servicesDescriptors.set(SILO_CONTEXT, { | ||
service: siloContext | ||
}); // Create a provider for the shutdown special dependency | ||
siloContext.servicesDescriptors.set(DISPOSE, { | ||
service: function () { | ||
var _ref3 = _asyncToGenerator(function* () { | ||
siloContext.shutdownPromise = siloContext.shutdownPromise || _shutdownNextServices(siloContext.servicesSequence); | ||
debug('Shutting down services'); | ||
yield siloContext.shutdownPromise; | ||
siloContext.servicesDescriptors.set(DISPOSE, { | ||
service: async () => { | ||
siloContext.shutdownPromise = siloContext.shutdownPromise || _shutdownNextServices(siloContext.servicesSequence); | ||
debug('Shutting down services'); | ||
await siloContext.shutdownPromise; | ||
_this3._silosContexts.delete(siloContext); // Shutdown services in their instanciation order | ||
this._silosContexts.delete(siloContext); // Shutdown services in their instanciation order | ||
function _shutdownNextServices(_x2) { | ||
return _shutdownNextServices2.apply(this, arguments); | ||
} | ||
async function _shutdownNextServices(reversedServiceSequence) { | ||
if (0 === reversedServiceSequence.length) { | ||
return; | ||
} | ||
function _shutdownNextServices2() { | ||
_shutdownNextServices2 = _asyncToGenerator(function* (reversedServiceSequence) { | ||
if (0 === reversedServiceSequence.length) { | ||
return; | ||
} | ||
await Promise.all(reversedServiceSequence.pop().map(async serviceName => { | ||
const singletonServiceDescriptor = await _this._pickupSingletonServiceDescriptorPromise(serviceName); | ||
const serviceDescriptor = singletonServiceDescriptor || (await siloContext.servicesDescriptors.get(serviceName)); | ||
let serviceShutdownPromise = _this._singletonsServicesShutdownsPromises.get(serviceName) || siloContext.servicesShutdownsPromises.get(serviceName); | ||
yield Promise.all(reversedServiceSequence.pop().map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref4 = _asyncToGenerator(function* (serviceName) { | ||
const singletonServiceDescriptor = yield _this._pickupSingletonServiceDescriptorPromise(serviceName); | ||
const serviceDescriptor = singletonServiceDescriptor || (yield siloContext.servicesDescriptors.get(serviceName)); | ||
let serviceShutdownPromise = _this._singletonsServicesShutdownsPromises.get(serviceName) || siloContext.servicesShutdownsPromises.get(serviceName); | ||
if (serviceShutdownPromise) { | ||
debug('Reusing a service shutdown promise:', serviceName); | ||
return serviceShutdownPromise; | ||
} | ||
if (serviceShutdownPromise) { | ||
debug('Reusing a service shutdown promise:', serviceName); | ||
return serviceShutdownPromise; | ||
} | ||
if (reversedServiceSequence.some(servicesDeclarations => servicesDeclarations.includes(serviceName))) { | ||
debug('Delaying service shutdown:', serviceName); | ||
return Promise.resolve(); | ||
} | ||
if (reversedServiceSequence.some(servicesDeclarations => servicesDeclarations.includes(serviceName))) { | ||
debug('Delaying service shutdown:', serviceName); | ||
return Promise.resolve(); | ||
} | ||
if (singletonServiceDescriptor) { | ||
const handleSet = _this._singletonsServicesHandles.get(serviceName); | ||
if (singletonServiceDescriptor) { | ||
const handleSet = _this._singletonsServicesHandles.get(serviceName); | ||
handleSet.delete(siloContext.name); | ||
handleSet.delete(siloContext.name); | ||
if (handleSet.size) { | ||
debug('Singleton is used elsewhere:', serviceName, handleSet); | ||
return Promise.resolve(); | ||
} | ||
if (handleSet.size) { | ||
debug('Singleton is used elsewhere:', serviceName, handleSet); | ||
return Promise.resolve(); | ||
} | ||
_this._singletonsServicesDescriptors.delete(serviceName); | ||
} | ||
_this._singletonsServicesDescriptors.delete(serviceName); | ||
} | ||
debug('Shutting down a service:', serviceName); | ||
serviceShutdownPromise = serviceDescriptor.dispose ? serviceDescriptor.dispose() : Promise.resolve(); | ||
debug('Shutting down a service:', serviceName); | ||
serviceShutdownPromise = serviceDescriptor.dispose ? serviceDescriptor.dispose() : Promise.resolve(); | ||
if (singletonServiceDescriptor) { | ||
_this._singletonsServicesShutdownsPromises.set(serviceName, serviceShutdownPromise); | ||
} | ||
siloContext.servicesShutdownsPromises.set(serviceName, serviceShutdownPromise); | ||
return serviceShutdownPromise; | ||
}); | ||
return function (_x3) { | ||
return _ref4.apply(this, arguments); | ||
}; | ||
}())); | ||
yield _shutdownNextServices(reversedServiceSequence); | ||
}); | ||
return _shutdownNextServices2.apply(this, arguments); | ||
if (singletonServiceDescriptor) { | ||
_this._singletonsServicesShutdownsPromises.set(serviceName, serviceShutdownPromise); | ||
} | ||
}); | ||
return function service() { | ||
return _ref3.apply(this, arguments); | ||
}; | ||
}(), | ||
dispose: Promise.resolve.bind(Promise) | ||
}); | ||
siloContext.servicesShutdownsPromises.set(serviceName, serviceShutdownPromise); | ||
return serviceShutdownPromise; | ||
})); | ||
await _shutdownNextServices(reversedServiceSequence); | ||
} | ||
}, | ||
dispose: Promise.resolve.bind(Promise) | ||
}); | ||
_this3._silosContexts.add(siloContext); | ||
this._silosContexts.add(siloContext); | ||
const servicesHash = yield _this3._initializeDependencies(siloContext, siloContext.name, internalDependencies, { | ||
injectOnly: false, | ||
autoloading: false | ||
}); | ||
debug('Handling fatal errors:', siloContext.errorsPromises); | ||
Promise.all(siloContext.errorsPromises).catch(siloContext.throwFatalError); | ||
return dependenciesDeclarations.reduce((finalHash, dependencyDeclaration) => { | ||
const { | ||
serviceName, | ||
mappedName | ||
} = (0, _util.parseDependencyDeclaration)(dependencyDeclaration); | ||
finalHash[serviceName] = servicesHash[mappedName]; | ||
return finalHash; | ||
}, {}); | ||
})(); | ||
const servicesHash = await this._initializeDependencies(siloContext, siloContext.name, internalDependencies, { | ||
injectOnly: false, | ||
autoloading: false | ||
}); | ||
debug('Handling fatal errors:', siloContext.errorsPromises); | ||
Promise.all(siloContext.errorsPromises).catch(siloContext.throwFatalError); | ||
return dependenciesDeclarations.reduce((finalHash, dependencyDeclaration) => { | ||
const { | ||
serviceName, | ||
mappedName | ||
} = (0, _util.parseDependencyDeclaration)(dependencyDeclaration); | ||
finalHash[serviceName] = servicesHash[mappedName]; | ||
return finalHash; | ||
}, {}); | ||
} | ||
@@ -620,140 +589,131 @@ /** | ||
_getServiceDescriptor(siloContext, serviceName, { | ||
async _getServiceDescriptor(siloContext, serviceName, { | ||
injectOnly, | ||
autoloading | ||
}) { | ||
var _this4 = this; | ||
// Try to get service descriptior early from the silo context | ||
let serviceDescriptorPromise = siloContext.servicesDescriptors.get(serviceName); | ||
return _asyncToGenerator(function* () { | ||
// Try to get service descriptior early from the silo context | ||
let serviceDescriptorPromise = siloContext.servicesDescriptors.get(serviceName); | ||
if (serviceDescriptorPromise) { | ||
return serviceDescriptorPromise; | ||
} | ||
if (serviceDescriptorPromise) { | ||
return serviceDescriptorPromise; | ||
} | ||
let initializer = await this._findInitializer(siloContext, serviceName, { | ||
injectOnly, | ||
autoloading | ||
}); | ||
serviceDescriptorPromise = this._pickupSingletonServiceDescriptorPromise(serviceName); | ||
let initializer = yield _this4._findInitializer(siloContext, serviceName, { | ||
injectOnly, | ||
autoloading | ||
}); | ||
serviceDescriptorPromise = _this4._pickupSingletonServiceDescriptorPromise(serviceName); | ||
if (serviceDescriptorPromise) { | ||
this._singletonsServicesHandles.get(serviceName).add(siloContext.name); | ||
} else { | ||
serviceDescriptorPromise = siloContext.servicesDescriptors.get(serviceName); | ||
} | ||
if (serviceDescriptorPromise) { | ||
_this4._singletonsServicesHandles.get(serviceName).add(siloContext.name); | ||
} else { | ||
serviceDescriptorPromise = siloContext.servicesDescriptors.get(serviceName); | ||
} | ||
if (serviceDescriptorPromise) { | ||
return serviceDescriptorPromise; | ||
} // The inject service is intended to be used as a workaround for unavoidable | ||
// circular dependencies. It wouldn't make sense to instanciate new services | ||
// at this level so throwing an error | ||
if (serviceDescriptorPromise) { | ||
return serviceDescriptorPromise; | ||
} // The inject service is intended to be used as a workaround for unavoidable | ||
// circular dependencies. It wouldn't make sense to instanciate new services | ||
// at this level so throwing an error | ||
if (injectOnly) { | ||
return Promise.reject(new _yerror.default(E_BAD_INJECTION, serviceName)); | ||
} | ||
if (injectOnly) { | ||
return Promise.reject(new _yerror.default(E_BAD_INJECTION, serviceName)); | ||
} | ||
serviceDescriptorPromise = this._initializeServiceDescriptor(siloContext, serviceName, initializer, { | ||
autoloading: autoloading || AUTOLOAD === serviceName, | ||
injectOnly | ||
}); | ||
serviceDescriptorPromise = _this4._initializeServiceDescriptor(siloContext, serviceName, initializer, { | ||
autoloading: autoloading || AUTOLOAD === serviceName, | ||
injectOnly | ||
}); | ||
if (initializer[_util.SPECIAL_PROPS.OPTIONS].singleton) { | ||
const handlesSet = new Set(); | ||
handlesSet.add(siloContext.name); | ||
if (initializer[_util.SPECIAL_PROPS.OPTIONS].singleton) { | ||
const handlesSet = new Set(); | ||
handlesSet.add(siloContext.name); | ||
this._singletonsServicesHandles.set(serviceName, handlesSet); | ||
_this4._singletonsServicesHandles.set(serviceName, handlesSet); | ||
this._singletonsServicesDescriptors.set(serviceName, { | ||
preloaded: false, | ||
promise: serviceDescriptorPromise | ||
}); | ||
} else { | ||
siloContext.servicesDescriptors.set(serviceName, serviceDescriptorPromise); | ||
} // Since the autoloader is a bit special it must be pushed here | ||
_this4._singletonsServicesDescriptors.set(serviceName, { | ||
preloaded: false, | ||
promise: serviceDescriptorPromise | ||
}); | ||
} else { | ||
siloContext.servicesDescriptors.set(serviceName, serviceDescriptorPromise); | ||
} // Since the autoloader is a bit special it must be pushed here | ||
if (AUTOLOAD === this.serviceName) { | ||
siloContext.servicesSequence.unshift([AUTOLOAD]); | ||
} | ||
if (AUTOLOAD === _this4.serviceName) { | ||
siloContext.servicesSequence.unshift([AUTOLOAD]); | ||
} | ||
return serviceDescriptorPromise; | ||
})(); | ||
return serviceDescriptorPromise; | ||
} | ||
_findInitializer(siloContext, serviceName, { | ||
async _findInitializer(siloContext, serviceName, { | ||
injectOnly, | ||
autoloading | ||
}) { | ||
var _this5 = this; | ||
let initializer = this._initializers.get(serviceName); | ||
return _asyncToGenerator(function* () { | ||
let initializer = _this5._initializers.get(serviceName); | ||
if (initializer) { | ||
return initializer; | ||
} // The auto loader must only have static dependencies | ||
// and we have to do this check here to avoid caching | ||
// non-autoloading request and then be blocked by an | ||
// autoloader dep that waits for that cached load | ||
if (initializer) { | ||
return initializer; | ||
} // The auto loader must only have static dependencies | ||
// and we have to do this check here to avoid caching | ||
// non-autoloading request and then be blocked by an | ||
// autoloader dep that waits for that cached load | ||
if (autoloading) { | ||
throw new _yerror.default(E_AUTOLOADER_DYNAMIC_DEPENDENCY, serviceName); | ||
} | ||
if (autoloading) { | ||
throw new _yerror.default(E_AUTOLOADER_DYNAMIC_DEPENDENCY, serviceName); | ||
} | ||
debug('No service provider:', serviceName); | ||
debug('No service provider:', serviceName); | ||
let initializerPromise = this._initializerResolvers.get(serviceName); | ||
let initializerPromise = _this5._initializerResolvers.get(serviceName); | ||
if (initializerPromise) { | ||
return await initializerPromise; | ||
} | ||
if (initializerPromise) { | ||
return yield initializerPromise; | ||
initializerPromise = (async () => { | ||
if (!this._initializers.get(AUTOLOAD)) { | ||
throw new _yerror.default(E_UNMATCHED_DEPENDENCY, serviceName); | ||
} | ||
initializerPromise = _asyncToGenerator(function* () { | ||
if (!_this5._initializers.get(AUTOLOAD)) { | ||
throw new _yerror.default(E_UNMATCHED_DEPENDENCY, serviceName); | ||
} | ||
debug(`Loading the $autoload service to lookup for: ${serviceName}.`); | ||
debug(`Loading the $autoload service to lookup for: ${serviceName}.`); | ||
try { | ||
const autoloadingDescriptor = await this._getServiceDescriptor(siloContext, AUTOLOAD, { | ||
injectOnly, | ||
autoloading: true | ||
}); | ||
const { | ||
initializer, | ||
path | ||
} = await autoloadingDescriptor.service(serviceName); | ||
try { | ||
const autoloadingDescriptor = yield _this5._getServiceDescriptor(siloContext, AUTOLOAD, { | ||
injectOnly, | ||
autoloading: true | ||
}); | ||
const { | ||
initializer, | ||
path | ||
} = yield autoloadingDescriptor.service(serviceName); | ||
if (typeof initializer !== 'function') { | ||
throw new _yerror.default(E_BAD_AUTOLOADED_INITIALIZER, serviceName, initializer); | ||
} | ||
if (typeof initializer !== 'function') { | ||
throw new _yerror.default(E_BAD_AUTOLOADED_INITIALIZER, serviceName, initializer); | ||
} | ||
if (initializer[_util.SPECIAL_PROPS.NAME] !== serviceName) { | ||
throw new _yerror.default(E_AUTOLOADED_INITIALIZER_MISMATCH, serviceName, initializer[_util.SPECIAL_PROPS.NAME]); | ||
} | ||
if (initializer[_util.SPECIAL_PROPS.NAME] !== serviceName) { | ||
throw new _yerror.default(E_AUTOLOADED_INITIALIZER_MISMATCH, serviceName, initializer[_util.SPECIAL_PROPS.NAME]); | ||
} | ||
debug(`Loaded the ${serviceName} initializer at path ${path}.`); | ||
this.register(initializer); | ||
debug(`Loaded the ${serviceName} initializer at path ${path}.`); | ||
this._initializerResolvers.delete(serviceName); // Here we need to pick-up the registered initializer to | ||
// have a universally usable intitializer | ||
_this5.register(initializer); | ||
_this5._initializerResolvers.delete(serviceName); // Here we need to pick-up the registered initializer to | ||
// have a universally usable intitializer | ||
return this._initializers.get(serviceName); | ||
} catch (err) { | ||
debug(`Could not load ${serviceName} via the auto loader.`); | ||
throw err; | ||
} | ||
})(); | ||
this._initializerResolvers.set(serviceName, initializerPromise); | ||
return _this5._initializers.get(serviceName); | ||
} catch (err) { | ||
debug(`Could not load ${serviceName} via the auto loader.`); | ||
throw err; | ||
} | ||
})(); | ||
_this5._initializerResolvers.set(serviceName, initializerPromise); | ||
return yield initializerPromise; | ||
})(); | ||
return await initializerPromise; | ||
} | ||
@@ -785,62 +745,58 @@ | ||
_initializeServiceDescriptor(siloContext, serviceName, initializer, { | ||
async _initializeServiceDescriptor(siloContext, serviceName, initializer, { | ||
autoloading, | ||
injectOnly | ||
}) { | ||
var _this6 = this; | ||
let serviceDescriptor; | ||
debug('Initializing a service descriptor:', serviceName); | ||
return _asyncToGenerator(function* () { | ||
let serviceDescriptor; | ||
debug('Initializing a service descriptor:', serviceName); | ||
try { | ||
// A singleton service may use a reserved resource | ||
// like a TCP socket. This is why we have to be aware | ||
// of singleton services full shutdown before creating | ||
// a new one | ||
await (this._singletonsServicesShutdownsPromises.get(serviceName) || Promise.resolve()); // Anyway delete any shutdown promise before instanciating | ||
// a new service | ||
try { | ||
// A singleton service may use a reserved resource | ||
// like a TCP socket. This is why we have to be aware | ||
// of singleton services full shutdown before creating | ||
// a new one | ||
yield _this6._singletonsServicesShutdownsPromises.get(serviceName) || Promise.resolve(); // Anyway delete any shutdown promise before instanciating | ||
// a new service | ||
this._singletonsServicesShutdownsPromises.delete(serviceName); | ||
_this6._singletonsServicesShutdownsPromises.delete(serviceName); | ||
siloContext.servicesShutdownsPromises.delete(serviceName); | ||
const servicesHash = await this._initializeDependencies(siloContext, serviceName, initializer[_util.SPECIAL_PROPS.INJECT], { | ||
injectOnly, | ||
autoloading | ||
}); | ||
debug('Successfully gathered service dependencies:', serviceName); | ||
serviceDescriptor = await initializer(initializer[_util.SPECIAL_PROPS.INJECT].reduce((finalHash, dependencyDeclaration) => { | ||
const { | ||
serviceName, | ||
mappedName | ||
} = (0, _util.parseDependencyDeclaration)(dependencyDeclaration); | ||
finalHash[serviceName] = servicesHash[mappedName]; | ||
return finalHash; | ||
}, {})); | ||
siloContext.servicesShutdownsPromises.delete(serviceName); | ||
const servicesHash = yield _this6._initializeDependencies(siloContext, serviceName, initializer[_util.SPECIAL_PROPS.INJECT], { | ||
injectOnly, | ||
autoloading | ||
}); | ||
debug('Successfully gathered service dependencies:', serviceName); | ||
serviceDescriptor = yield initializer(initializer[_util.SPECIAL_PROPS.INJECT].reduce((finalHash, dependencyDeclaration) => { | ||
const { | ||
serviceName, | ||
mappedName | ||
} = (0, _util.parseDependencyDeclaration)(dependencyDeclaration); | ||
finalHash[serviceName] = servicesHash[mappedName]; | ||
return finalHash; | ||
}, {})); | ||
if (!serviceDescriptor) { | ||
debug('Provider did not return a descriptor:', serviceName); | ||
return Promise.reject(new _yerror.default(E_BAD_SERVICE_PROVIDER, serviceName)); | ||
} | ||
if (!serviceDescriptor) { | ||
debug('Provider did not return a descriptor:', serviceName); | ||
return Promise.reject(new _yerror.default(E_BAD_SERVICE_PROVIDER, serviceName)); | ||
} | ||
debug('Successfully initialized a service descriptor:', serviceName); | ||
debug('Successfully initialized a service descriptor:', serviceName); | ||
if (serviceDescriptor.fatalErrorPromise) { | ||
debug('Registering service descriptor error promise:', serviceName); | ||
siloContext.errorsPromises.push(serviceDescriptor.fatalErrorPromise); | ||
} | ||
if (serviceDescriptor.fatalErrorPromise) { | ||
debug('Registering service descriptor error promise:', serviceName); | ||
siloContext.errorsPromises.push(serviceDescriptor.fatalErrorPromise); | ||
} | ||
siloContext.servicesDescriptors.set(serviceName, serviceDescriptor); | ||
} catch (err) { | ||
debug('Error initializing a service descriptor:', serviceName, err.stack); | ||
siloContext.servicesDescriptors.set(serviceName, serviceDescriptor); | ||
} catch (err) { | ||
debug('Error initializing a service descriptor:', serviceName, err.stack); | ||
if (E_UNMATCHED_DEPENDENCY === err.code) { | ||
throw _yerror.default.wrap(...[err, E_UNMATCHED_DEPENDENCY, serviceName].concat(err.params)); | ||
} | ||
if (E_UNMATCHED_DEPENDENCY === err.code) { | ||
throw _yerror.default.wrap(...[err, E_UNMATCHED_DEPENDENCY, serviceName].concat(err.params)); | ||
} | ||
throw err; | ||
} | ||
throw err; | ||
} | ||
return serviceDescriptor; | ||
})(); | ||
return serviceDescriptor; | ||
} | ||
@@ -862,62 +818,42 @@ /** | ||
_initializeDependencies(siloContext, serviceName, servicesDeclarations, { | ||
async _initializeDependencies(siloContext, serviceName, servicesDeclarations, { | ||
injectOnly = false, | ||
autoloading = false | ||
}) { | ||
var _this7 = this; | ||
debug('Initializing dependencies:', serviceName, servicesDeclarations); | ||
const servicesDescriptors = await Promise.all(servicesDeclarations.map(async serviceDeclaration => { | ||
const { | ||
mappedName, | ||
optional | ||
} = (0, _util.parseDependencyDeclaration)(serviceDeclaration); | ||
return _asyncToGenerator(function* () { | ||
debug('Initializing dependencies:', serviceName, servicesDeclarations); | ||
const servicesDescriptors = yield Promise.all(servicesDeclarations.map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref6 = _asyncToGenerator(function* (serviceDeclaration) { | ||
const { | ||
mappedName, | ||
optional | ||
} = (0, _util.parseDependencyDeclaration)(serviceDeclaration); | ||
try { | ||
const serviceDescriptor = yield _this7._getServiceDescriptor(siloContext, mappedName, { | ||
injectOnly, | ||
autoloading | ||
}); | ||
return serviceDescriptor; | ||
} catch (err) { | ||
if (optional) { | ||
return; | ||
} | ||
throw err; | ||
} | ||
try { | ||
const serviceDescriptor = await this._getServiceDescriptor(siloContext, mappedName, { | ||
injectOnly, | ||
autoloading | ||
}); | ||
return serviceDescriptor; | ||
} catch (err) { | ||
if (optional) { | ||
return; | ||
} | ||
return function (_x4) { | ||
return _ref6.apply(this, arguments); | ||
}; | ||
}())); | ||
debug('Initialized dependencies descriptors:', serviceName, servicesDeclarations, servicesDescriptors); | ||
siloContext.servicesSequence.push(servicesDeclarations.filter((_, index) => servicesDescriptors[index]).map(_pickMappedNameFromDeclaration)); | ||
const services = yield Promise.all(servicesDescriptors.map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref7 = _asyncToGenerator(function* (serviceDescriptor) { | ||
if (!serviceDescriptor) { | ||
return {}.undef; | ||
} | ||
throw err; | ||
} | ||
})); | ||
debug('Initialized dependencies descriptors:', serviceName, servicesDeclarations, servicesDescriptors); | ||
siloContext.servicesSequence.push(servicesDeclarations.filter((_, index) => servicesDescriptors[index]).map(_pickMappedNameFromDeclaration)); | ||
const services = await Promise.all(servicesDescriptors.map(async serviceDescriptor => { | ||
if (!serviceDescriptor) { | ||
return {}.undef; | ||
} | ||
return serviceDescriptor.service; | ||
}); | ||
return serviceDescriptor.service; | ||
})); | ||
return services.reduce((hash, service, index) => { | ||
const mappedName = _pickMappedNameFromDeclaration(servicesDeclarations[index]); | ||
return function (_x5) { | ||
return _ref7.apply(this, arguments); | ||
}; | ||
}())); | ||
return services.reduce((hash, service, index) => { | ||
const mappedName = _pickMappedNameFromDeclaration(servicesDeclarations[index]); | ||
hash[mappedName] = service; | ||
return hash; | ||
}, {}); | ||
})(); | ||
hash[mappedName] = service; | ||
return hash; | ||
}, {}); | ||
} | ||
@@ -924,0 +860,0 @@ |
@@ -15,6 +15,3 @@ "use strict"; | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
/* eslint max-nested-callbacks:0 */ | ||
describe('Knifecycle', () => { | ||
@@ -48,18 +45,14 @@ let $; | ||
}); | ||
it('should work when overriding a previously set constant', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
it('should work when overriding a previously set constant', async () => { | ||
$.register((0, _index.constant)('TEST', 1)); | ||
$.register((0, _index.constant)('TEST', 2)); | ||
_assert.default.deepEqual((yield $.run(['TEST'])), { | ||
_assert.default.deepEqual((await $.run(['TEST'])), { | ||
TEST: 2 | ||
}); | ||
})); | ||
it('should fail when overriding an initialized constant', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail when overriding an initialized constant', async () => { | ||
$.register((0, _index.constant)('TEST', 1)); | ||
_assert.default.deepEqual((yield $.run(['TEST'])), { | ||
_assert.default.deepEqual((await $.run(['TEST'])), { | ||
TEST: 1 | ||
@@ -74,3 +67,3 @@ }); | ||
} | ||
})); | ||
}); | ||
}); | ||
@@ -81,32 +74,16 @@ describe('with services', () => { | ||
}); | ||
it('should work when overriding a previously set service', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
$.register((0, _index.service)('test', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return () => 1; | ||
}))); | ||
$.register((0, _index.service)('test', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return () => 2; | ||
}))); | ||
it('should work when overriding a previously set service', async () => { | ||
$.register((0, _index.service)('test', async () => () => 1)); | ||
$.register((0, _index.service)('test', async () => () => 2)); | ||
const { | ||
test | ||
} = yield $.run(['test']); | ||
} = await $.run(['test']); | ||
_assert.default.deepEqual(test(), 2); | ||
})); | ||
it('should fail when overriding an initialized service', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
$.register((0, _index.service)('test', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return () => 1; | ||
}))); | ||
}); | ||
it('should fail when overriding an initialized service', async () => { | ||
$.register((0, _index.service)('test', async () => () => 1)); | ||
const { | ||
test | ||
} = yield $.run(['test']); | ||
} = await $.run(['test']); | ||
@@ -116,7 +93,3 @@ _assert.default.deepEqual(test(), 1); | ||
try { | ||
$.register((0, _index.service)('test', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return () => 2; | ||
}))); | ||
$.register((0, _index.service)('test', async () => () => 2)); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
@@ -126,3 +99,3 @@ } catch (err) { | ||
} | ||
})); | ||
}); | ||
}); | ||
@@ -133,5 +106,3 @@ describe('with providers', () => { | ||
}); | ||
it('should work when overriding a previously set provider', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
it('should work when overriding a previously set provider', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -141,8 +112,4 @@ type: 'provider', | ||
inject: [] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return { | ||
service: 1 | ||
}; | ||
}, async () => ({ | ||
service: 1 | ||
}))); | ||
@@ -153,18 +120,12 @@ $.register((0, _index.initializer)({ | ||
inject: [] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return { | ||
service: 2 | ||
}; | ||
}, async () => ({ | ||
service: 2 | ||
}))); | ||
const { | ||
test | ||
} = yield $.run(['test']); | ||
} = await $.run(['test']); | ||
_assert.default.deepEqual(test, 2); | ||
})); | ||
it('should work when overriding a previously set singleton provider', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work when overriding a previously set singleton provider', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -177,8 +138,4 @@ type: 'provider', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return { | ||
service: 1 | ||
}; | ||
}, async () => ({ | ||
service: 1 | ||
}))); | ||
@@ -189,18 +146,12 @@ $.register((0, _index.initializer)({ | ||
inject: [] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return { | ||
service: 2 | ||
}; | ||
}, async () => ({ | ||
service: 2 | ||
}))); | ||
const { | ||
test | ||
} = yield $.run(['test']); | ||
} = await $.run(['test']); | ||
_assert.default.deepEqual(test, 2); | ||
})); | ||
it('should fail when overriding an initialized provider', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail when overriding an initialized provider', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -213,12 +164,8 @@ type: 'provider', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return { | ||
service: 1 | ||
}; | ||
}, async () => ({ | ||
service: 1 | ||
}))); | ||
const { | ||
test | ||
} = yield $.run(['test']); | ||
} = await $.run(['test']); | ||
@@ -232,8 +179,4 @@ _assert.default.deepEqual(test, 1); | ||
inject: [] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return { | ||
service: 2 | ||
}; | ||
}, async () => ({ | ||
service: 2 | ||
}))); | ||
@@ -244,3 +187,3 @@ throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
} | ||
})); | ||
}); | ||
}); | ||
@@ -423,15 +366,11 @@ it('should fail when intitializer is no a function', () => { | ||
describe('run', () => { | ||
it('should work with no dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
const dependencies = yield $.run([]); | ||
it('should work with no dependencies', async () => { | ||
const dependencies = await $.run([]); | ||
_assert.default.deepEqual(dependencies, {}); | ||
})); | ||
it('should work with constant dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with constant dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
const dependencies = yield $.run(['time', 'ENV']); | ||
const dependencies = await $.run(['time', 'ENV']); | ||
@@ -444,6 +383,4 @@ _assert.default.deepEqual(Object.keys(dependencies), ['time', 'ENV']); | ||
}); | ||
})); | ||
it('should work with service dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with service dependencies', async () => { | ||
$.register((0, _index.service)('sample', (0, _index.inject)(['time'], function sampleService({ | ||
@@ -455,3 +392,3 @@ time | ||
$.register((0, _index.constant)('time', time)); | ||
const dependencies = yield $.run(['sample']); | ||
const dependencies = await $.run(['sample']); | ||
@@ -463,10 +400,8 @@ _assert.default.deepEqual(Object.keys(dependencies), ['sample']); | ||
}); | ||
})); | ||
it('should work with simple dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with simple dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV'], hashProvider))); | ||
const dependencies = yield $.run(['time', 'hash']); | ||
const dependencies = await $.run(['time', 'hash']); | ||
@@ -481,6 +416,4 @@ _assert.default.deepEqual(Object.keys(dependencies), ['time', 'hash']); | ||
}); | ||
})); | ||
it('should work with given optional dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with given optional dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -490,3 +423,3 @@ $.register((0, _index.constant)('DEBUG', {})); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV', '?DEBUG'], hashProvider))); | ||
const dependencies = yield $.run(['time', 'hash']); | ||
const dependencies = await $.run(['time', 'hash']); | ||
@@ -502,10 +435,8 @@ _assert.default.deepEqual(Object.keys(dependencies), ['time', 'hash']); | ||
}); | ||
})); | ||
it('should work with lacking optional dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with lacking optional dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV', '?DEBUG'], hashProvider))); | ||
const dependencies = yield $.run(['time', 'hash']); | ||
const dependencies = await $.run(['time', 'hash']); | ||
@@ -521,6 +452,4 @@ _assert.default.deepEqual(Object.keys(dependencies), ['time', 'hash']); | ||
}); | ||
})); | ||
it('should work with deeper dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with deeper dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -534,9 +463,7 @@ $.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash5', (0, _index.inject)(['hash4'], hashProvider))); | ||
const dependencies = yield $.run(['hash5', 'time']); | ||
const dependencies = await $.run(['hash5', 'time']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['hash5', 'time']); | ||
})); | ||
it('should instanciate services once', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should instanciate services once', async () => { | ||
const timeServiceStub = _sinon.default.spy(timeService); | ||
@@ -549,3 +476,3 @@ | ||
$.register((0, _index.provider)('hash3', (0, _index.inject)(['ENV', 'time'], hashProvider))); | ||
const dependencies = yield $.run(['hash', 'hash2', 'hash3', 'time']); | ||
const dependencies = await $.run(['hash', 'hash2', 'hash3', 'time']); | ||
@@ -555,6 +482,4 @@ _assert.default.deepEqual(Object.keys(dependencies), ['hash', 'hash2', 'hash3', 'time']); | ||
_assert.default.deepEqual(timeServiceStub.args, [[{}]]); | ||
})); | ||
it('should instanciate a single mapped service', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should instanciate a single mapped service', async () => { | ||
const providerStub = _sinon.default.stub().returns(Promise.resolve({ | ||
@@ -570,3 +495,3 @@ service: 'stub' | ||
$.register((0, _index.provider)('mappedStub2', providerStub2)); | ||
const dependencies = yield $.run(['stub>mappedStub']); | ||
const dependencies = await $.run(['stub>mappedStub']); | ||
@@ -580,6 +505,4 @@ _assert.default.deepEqual(dependencies, { | ||
}]]); | ||
})); | ||
it('should instanciate several services with mappings', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should instanciate several services with mappings', async () => { | ||
const timeServiceStub = _sinon.default.spy(timeService); | ||
@@ -592,3 +515,3 @@ | ||
$.register((0, _index.provider)('aHash3', (0, _index.inject)(['ENV', 'hash>aHash'], hashProvider))); | ||
const dependencies = yield $.run(['hash2>aHash2', 'hash3>aHash3', 'time>aTime']); | ||
const dependencies = await $.run(['hash2>aHash2', 'hash3>aHash3', 'time>aTime']); | ||
@@ -598,10 +521,8 @@ _assert.default.deepEqual(Object.keys(dependencies), ['hash2', 'hash3', 'time']); | ||
_assert.default.deepEqual(timeServiceStub.args, [[{}]]); | ||
})); | ||
it('should fail with bad service', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail with bad service', async () => { | ||
$.register((0, _index.service)('lol', () => {})); | ||
try { | ||
yield $.run(['lol']); | ||
await $.run(['lol']); | ||
throw new Error('E_UNEXPECTED_SUCCESS'); | ||
@@ -613,10 +534,8 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail with bad provider', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail with bad provider', async () => { | ||
$.register((0, _index.provider)('lol', () => {})); | ||
try { | ||
yield $.run(['lol']); | ||
await $.run(['lol']); | ||
throw new Error('E_UNEXPECTED_SUCCESS'); | ||
@@ -628,10 +547,8 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail with bad service in a provider', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail with bad service in a provider', async () => { | ||
$.register((0, _index.provider)('lol', () => Promise.resolve())); | ||
try { | ||
yield $.run(['lol']); | ||
await $.run(['lol']); | ||
throw new Error('E_UNEXPECTED_SUCCESS'); | ||
@@ -643,8 +560,6 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail with undeclared dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail with undeclared dependencies', async () => { | ||
try { | ||
yield $.run(['lol']); | ||
await $.run(['lol']); | ||
throw new Error('E_UNEXPECTED_SUCCESS'); | ||
@@ -656,6 +571,4 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail with undeclared dependencies upstream', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail with undeclared dependencies upstream', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -667,3 +580,3 @@ $.register((0, _index.constant)('time', time)); | ||
try { | ||
yield $.run(['time', 'hash']); | ||
await $.run(['time', 'hash']); | ||
throw new Error('E_UNEXPECTED_SUCCESS'); | ||
@@ -675,6 +588,4 @@ } catch (err) { | ||
} | ||
})); | ||
it('should provide a fatal error handler', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should provide a fatal error handler', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -696,24 +607,17 @@ $.register((0, _index.constant)('time', time)); | ||
function dbProvider(_x) { | ||
return _dbProvider.apply(this, arguments); | ||
} | ||
function _dbProvider() { | ||
_dbProvider = _asyncToGenerator(function* ({ | ||
ENV | ||
}) { | ||
let service; | ||
const fatalErrorPromise = new Promise((resolve, reject) => { | ||
service = Promise.resolve({ | ||
resolve, | ||
reject, | ||
ENV | ||
}); | ||
async function dbProvider({ | ||
ENV | ||
}) { | ||
let service; | ||
const fatalErrorPromise = new Promise((resolve, reject) => { | ||
service = Promise.resolve({ | ||
resolve, | ||
reject, | ||
ENV | ||
}); | ||
return { | ||
service, | ||
fatalErrorPromise | ||
}; | ||
}); | ||
return _dbProvider.apply(this, arguments); | ||
return { | ||
service, | ||
fatalErrorPromise | ||
}; | ||
} | ||
@@ -724,7 +628,7 @@ | ||
db | ||
} = yield $.run(['time', 'hash', 'db', 'process']); | ||
} = await $.run(['time', 'hash', 'db', 'process']); | ||
try { | ||
db.reject(new Error('E_DB_ERROR')); | ||
yield process.fatalErrorPromise; | ||
await process.fatalErrorPromise; | ||
throw new Error('E_UNEXPECTED_SUCCESS'); | ||
@@ -734,8 +638,6 @@ } catch (err) { | ||
} | ||
})); | ||
}); | ||
}); | ||
describe('autoload', () => { | ||
it('should work with lacking autoloaded dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
it('should work with lacking autoloaded dependencies', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -748,28 +650,9 @@ type: 'service', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref36 = _asyncToGenerator(function* (serviceName) { | ||
return { | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'DEBUG', | ||
inject: [] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return 'THE_DEBUG:' + serviceName; | ||
})) | ||
}; | ||
}); | ||
return function (_x2) { | ||
return _ref36.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
}, async () => async serviceName => ({ | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'DEBUG', | ||
inject: [] | ||
}, async () => 'THE_DEBUG:' + serviceName) | ||
}))); | ||
@@ -779,3 +662,3 @@ $.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV', '?DEBUG'], hashProvider))); | ||
const dependencies = yield $.run(['time', 'hash']); | ||
const dependencies = await $.run(['time', 'hash']); | ||
@@ -791,6 +674,4 @@ _assert.default.deepEqual(Object.keys(dependencies), ['time', 'hash']); | ||
}); | ||
})); | ||
it('should work with deeper several lacking dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with deeper several lacking dependencies', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -802,24 +683,9 @@ name: '$autoload', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref40 = _asyncToGenerator(function* (serviceName) { | ||
return { | ||
path: `/path/to/${serviceName}`, | ||
initializer: (0, _index.initializer)({ | ||
type: 'provider', | ||
name: serviceName, | ||
inject: 'hash2' === serviceName ? ['hash1'] : 'hash4' === serviceName ? ['hash3'] : [] | ||
}, hashProvider) | ||
}; | ||
}); | ||
return function (_x3) { | ||
return _ref40.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
}, async () => async serviceName => ({ | ||
path: `/path/to/${serviceName}`, | ||
initializer: (0, _index.initializer)({ | ||
type: 'provider', | ||
name: serviceName, | ||
inject: 'hash2' === serviceName ? ['hash1'] : 'hash4' === serviceName ? ['hash3'] : [] | ||
}, hashProvider) | ||
}))); | ||
@@ -832,9 +698,7 @@ $.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.provider)('hash5', (0, _index.inject)(['hash4'], hashProvider))); | ||
const dependencies = yield $.run(['hash5', 'time']); | ||
const dependencies = await $.run(['hash5', 'time']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['hash5', 'time']); | ||
})); | ||
it('should work with various dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with various dependencies', async () => { | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['hash2'], hashProvider))); | ||
@@ -850,36 +714,15 @@ $.register((0, _index.provider)('hash3', (0, _index.inject)(['?ENV'], hashProvider))); | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref43 = _asyncToGenerator(function* (serviceName) { | ||
return { | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'hash2', | ||
inject: ['hash3'] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return 'THE_HASH:' + serviceName; | ||
})) | ||
}; | ||
}); | ||
return function (_x4) { | ||
return _ref43.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
}, async () => async serviceName => ({ | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'hash2', | ||
inject: ['hash3'] | ||
}, async () => 'THE_HASH:' + serviceName) | ||
}))); | ||
const dependencies = yield $.run(['hash', '?ENV']); | ||
const dependencies = await $.run(['hash', '?ENV']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['hash', 'ENV']); | ||
})); | ||
it('should instanciate services once', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should instanciate services once', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -891,24 +734,9 @@ name: '$autoload', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref47 = _asyncToGenerator(function* (serviceName) { | ||
return { | ||
path: `/path/to/${serviceName}`, | ||
initializer: (0, _index.initializer)({ | ||
type: 'provider', | ||
name: serviceName, | ||
inject: ['ENV', 'time'] | ||
}, hashProvider) | ||
}; | ||
}); | ||
return function (_x5) { | ||
return _ref47.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
}, async () => async serviceName => ({ | ||
path: `/path/to/${serviceName}`, | ||
initializer: (0, _index.initializer)({ | ||
type: 'provider', | ||
name: serviceName, | ||
inject: ['ENV', 'time'] | ||
}, hashProvider) | ||
}))); | ||
@@ -922,3 +750,3 @@ | ||
$.register((0, _index.provider)('hash_', (0, _index.inject)(['hash1', 'hash2', 'hash3'], hashProvider))); | ||
const dependencies = yield $.run(['hash', 'hash_', 'hash3']); | ||
const dependencies = await $.run(['hash', 'hash_', 'hash3']); | ||
@@ -928,8 +756,6 @@ _assert.default.deepEqual(timeServiceStub.args, [[{}]]); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['hash', 'hash_', 'hash3']); | ||
})); | ||
it('should fail when autoload does not exists', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail when autoload does not exists', async () => { | ||
try { | ||
yield $.run(['test']); | ||
await $.run(['test']); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
@@ -939,6 +765,4 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail when autoloaded dependencies are not found', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail when autoloaded dependencies are not found', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -951,21 +775,8 @@ type: 'service', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref51 = _asyncToGenerator(function* (serviceName) { | ||
throw new _yerror.default('E_CANNOT_AUTOLOAD', serviceName); | ||
}); | ||
}, async () => async serviceName => { | ||
throw new _yerror.default('E_CANNOT_AUTOLOAD', serviceName); | ||
})); | ||
return function (_x6) { | ||
return _ref51.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
}))); | ||
try { | ||
yield $.run(['test']); | ||
await $.run(['test']); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
@@ -977,6 +788,4 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail when autoloaded dependencies are not initializers', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail when autoloaded dependencies are not initializers', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -989,15 +798,6 @@ type: 'service', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return 'not_an_initializer'; | ||
}) | ||
); | ||
}))); | ||
}, async () => async () => 'not_an_initializer')); | ||
try { | ||
yield $.run(['test']); | ||
await $.run(['test']); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
@@ -1009,6 +809,4 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail when autoloaded dependencies are not right initializers', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail when autoloaded dependencies are not right initializers', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -1021,32 +819,13 @@ type: 'service', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref57 = _asyncToGenerator(function* (serviceName) { | ||
return { | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'not-' + serviceName, | ||
inject: [] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return 'THE_TEST:' + serviceName; | ||
})) | ||
}; | ||
}); | ||
return function (_x7) { | ||
return _ref57.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
}, async () => async serviceName => ({ | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'not-' + serviceName, | ||
inject: [] | ||
}, async () => 'THE_TEST:' + serviceName) | ||
}))); | ||
try { | ||
yield $.run(['test']); | ||
await $.run(['test']); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
@@ -1058,6 +837,4 @@ } catch (err) { | ||
} | ||
})); | ||
it('should fail when autoload depends on autoloaded/unexisting dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail when autoload depends on autoloaded/unexisting dependencies', async () => { | ||
$.register((0, _index.initializer)({ | ||
@@ -1070,32 +847,13 @@ type: 'service', | ||
} | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return ( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref61 = _asyncToGenerator(function* (serviceName) { | ||
return { | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'DEBUG', | ||
inject: [] | ||
}, | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
return 'THE_DEBUG:' + serviceName; | ||
})) | ||
}; | ||
}); | ||
return function (_x8) { | ||
return _ref61.apply(this, arguments); | ||
}; | ||
}() | ||
); | ||
}, async () => async serviceName => ({ | ||
path: '/path/of/debug', | ||
initializer: (0, _index.initializer)({ | ||
type: 'service', | ||
name: 'DEBUG', | ||
inject: [] | ||
}, async () => 'THE_DEBUG:' + serviceName) | ||
}))); | ||
try { | ||
yield $.run(['test']); | ||
await $.run(['test']); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
@@ -1107,16 +865,14 @@ } catch (err) { | ||
} | ||
})); | ||
}); | ||
}); | ||
describe('inject', () => { | ||
it('should work with no dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
it('should work with no dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV'], hashProvider))); | ||
const dependencies = yield $.run(['time', 'hash', '$injector']); | ||
const dependencies = await $.run(['time', 'hash', '$injector']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['time', 'hash', '$injector']); | ||
const injectDependencies = yield dependencies.$injector([]); | ||
const injectDependencies = await dependencies.$injector([]); | ||
@@ -1126,14 +882,12 @@ _assert.default.deepEqual(Object.keys(injectDependencies), []); | ||
_assert.default.deepEqual(injectDependencies, {}); | ||
})); | ||
it('should work with same dependencies then the running silo', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with same dependencies then the running silo', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV'], hashProvider))); | ||
const dependencies = yield $.run(['time', 'hash', '$injector']); | ||
const dependencies = await $.run(['time', 'hash', '$injector']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['time', 'hash', '$injector']); | ||
const injectDependencies = yield dependencies.$injector(['time', 'hash']); | ||
const injectDependencies = await dependencies.$injector(['time', 'hash']); | ||
@@ -1148,10 +902,8 @@ _assert.default.deepEqual(Object.keys(injectDependencies), ['time', 'hash']); | ||
}); | ||
})); | ||
it('should fail with non instanciated dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should fail with non instanciated dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV'], hashProvider))); | ||
const dependencies = yield $.run(['time', '$injector']); | ||
const dependencies = await $.run(['time', '$injector']); | ||
@@ -1161,3 +913,3 @@ _assert.default.deepEqual(Object.keys(dependencies), ['time', '$injector']); | ||
try { | ||
yield dependencies.$injector(['time', 'hash']); | ||
await dependencies.$injector(['time', 'hash']); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCESS'); | ||
@@ -1167,6 +919,4 @@ } catch (err) { | ||
} | ||
})); | ||
it('should create dependencies when not declared as singletons', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should create dependencies when not declared as singletons', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1178,3 +928,3 @@ $.register((0, _index.provider)('hash', (0, _index.inject)(['ENV'], hashProvider))); | ||
hash: sameHash | ||
}] = yield Promise.all([$.run(['hash']), $.run(['hash'])]); | ||
}] = await Promise.all([$.run(['hash']), $.run(['hash'])]); | ||
@@ -1185,9 +935,7 @@ _assert.default.notEqual(hash, sameHash); | ||
hash: yaSameHash | ||
} = yield $.run(['hash']); | ||
} = await $.run(['hash']); | ||
_assert.default.notEqual(hash, yaSameHash); | ||
})); | ||
it('should reuse dependencies when declared as singletons', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should reuse dependencies when declared as singletons', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1206,3 +954,3 @@ $.register((0, _index.provider)('hash', (0, _index.inject)(['ENV'], hashProvider), { | ||
hash2: sameHash2 | ||
}] = yield Promise.all([$.run(['hash']), $.run(['hash']), $.run(['hash2']), $.run(['hash2'])]); | ||
}] = await Promise.all([$.run(['hash']), $.run(['hash']), $.run(['hash2']), $.run(['hash2'])]); | ||
@@ -1215,20 +963,16 @@ _assert.default.equal(hash, sameHash); | ||
hash: yaSameHash | ||
} = yield $.run(['hash']); | ||
} = await $.run(['hash']); | ||
_assert.default.equal(hash, yaSameHash); | ||
})); | ||
}); | ||
}); | ||
describe('$destroy', () => { | ||
it('should work even with one silo and no dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
const dependencies = yield $.run(['$destroy']); | ||
it('should work even with one silo and no dependencies', async () => { | ||
const dependencies = await $.run(['$destroy']); | ||
_assert.default.equal(typeof dependencies.$destroy, 'function'); | ||
yield dependencies.$destroy(); | ||
})); | ||
it('should work with several silos and dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
await dependencies.$destroy(); | ||
}); | ||
it('should work with several silos and dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1241,11 +985,9 @@ $.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash2', (0, _index.inject)(['ENV'], hashProvider))); | ||
const [dependencies] = yield Promise.all([$.run(['$destroy']), $.run(['ENV', 'hash', 'hash1', 'time']), $.run(['ENV', 'hash', 'hash2'])]); | ||
const [dependencies] = await Promise.all([$.run(['$destroy']), $.run(['ENV', 'hash', 'hash1', 'time']), $.run(['ENV', 'hash', 'hash2'])]); | ||
_assert.default.equal(typeof dependencies.$destroy, 'function'); | ||
yield dependencies.$destroy(); | ||
})); | ||
it('should work when trigered from several silos simultaneously', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
await dependencies.$destroy(); | ||
}); | ||
it('should work when trigered from several silos simultaneously', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1256,8 +998,6 @@ $.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash2', (0, _index.inject)(['ENV'], hashProvider))); | ||
const dependenciesBuckets = yield Promise.all([$.run(['$destroy']), $.run(['$destroy', 'ENV', 'hash', 'hash1', 'time']), $.run(['$destroy', 'ENV', 'hash', 'hash2'])]); | ||
yield Promise.all(dependenciesBuckets.map(dependencies => dependencies.$destroy())); | ||
})); | ||
it('should work when a silo shutdown is in progress', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
const dependenciesBuckets = await Promise.all([$.run(['$destroy']), $.run(['$destroy', 'ENV', 'hash', 'hash1', 'time']), $.run(['$destroy', 'ENV', 'hash', 'hash2'])]); | ||
await Promise.all(dependenciesBuckets.map(dependencies => dependencies.$destroy())); | ||
}); | ||
it('should work when a silo shutdown is in progress', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1268,8 +1008,6 @@ $.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash2', (0, _index.inject)(['ENV'], hashProvider))); | ||
const [dependencies1, dependencies2] = yield Promise.all([$.run(['$destroy']), $.run(['$dispose', 'ENV', 'hash', 'hash1', 'time']), $.run(['ENV', 'hash', 'hash2'])]); | ||
yield Promise.all([dependencies2.$dispose(), dependencies1.$destroy()]); | ||
})); | ||
it('should disallow new runs', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
const [dependencies1, dependencies2] = await Promise.all([$.run(['$destroy']), $.run(['$dispose', 'ENV', 'hash', 'hash1', 'time']), $.run(['ENV', 'hash', 'hash2'])]); | ||
await Promise.all([dependencies2.$dispose(), dependencies1.$destroy()]); | ||
}); | ||
it('should disallow new runs', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1279,10 +1017,10 @@ $.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash1', (0, _index.inject)(['ENV'], hashProvider))); | ||
const dependencies = yield $.run(['$destroy']); | ||
const dependencies = await $.run(['$destroy']); | ||
_assert.default.equal(typeof dependencies.$destroy, 'function'); | ||
yield dependencies.$destroy(); | ||
await dependencies.$destroy(); | ||
try { | ||
yield $.run(['ENV', 'hash', 'hash1']); | ||
await $.run(['ENV', 'hash', 'hash1']); | ||
throw new _yerror.default('E_UNEXPECTED_SUCCES'); | ||
@@ -1292,9 +1030,7 @@ } catch (err) { | ||
} | ||
})); | ||
}); | ||
}); | ||
describe('$dispose', () => { | ||
it('should work with no dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
const dependencies = yield $.run(['$dispose']); | ||
it('should work with no dependencies', async () => { | ||
const dependencies = await $.run(['$dispose']); | ||
@@ -1304,29 +1040,23 @@ _assert.default.equal(typeof dependencies.$dispose, 'function'); | ||
return dependencies.$dispose(); | ||
})); | ||
it('should work with constant dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should work with constant dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
const dependencies = yield $.run(['time', 'ENV', '$dispose']); | ||
const dependencies = await $.run(['time', 'ENV', '$dispose']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['time', 'ENV', '$dispose']); | ||
yield dependencies.$dispose(); | ||
})); | ||
it('should work with simple dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
await dependencies.$dispose(); | ||
}); | ||
it('should work with simple dependencies', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
$.register((0, _index.constant)('time', time)); | ||
$.register((0, _index.provider)('hash', (0, _index.inject)(['ENV'], hashProvider))); | ||
const dependencies = yield $.run(['time', 'hash', '$dispose']); | ||
const dependencies = await $.run(['time', 'hash', '$dispose']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['time', 'hash', '$dispose']); | ||
yield dependencies.$dispose(); | ||
})); | ||
it('should work with deeper dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
await dependencies.$dispose(); | ||
}); | ||
it('should work with deeper dependencies', async () => { | ||
let shutdownCallResolve; | ||
@@ -1360,3 +1090,3 @@ let shutdownResolve; | ||
})))); | ||
const dependencies = yield $.run(['hash5', 'time', '$dispose', 'shutdownChecker']); | ||
const dependencies = await $.run(['hash5', 'time', '$dispose', 'shutdownChecker']); | ||
@@ -1370,8 +1100,6 @@ _assert.default.deepEqual(Object.keys(dependencies), ['hash5', 'time', '$dispose', 'shutdownChecker']); | ||
}); | ||
yield dependencies.$dispose(); | ||
yield finalPromise; | ||
})); | ||
it('should work with deeper multi used dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
await dependencies.$dispose(); | ||
await finalPromise; | ||
}); | ||
it('should work with deeper multi used dependencies', async () => { | ||
let shutdownCallResolve; | ||
@@ -1401,3 +1129,3 @@ let shutdownResolve; | ||
$.register((0, _index.provider)('hash2', (0, _index.inject)(['shutdownChecker'], hashProvider))); | ||
const dependencies = yield $.run(['hash1', 'hash2', '$dispose', 'shutdownChecker']); | ||
const dependencies = await $.run(['hash1', 'hash2', '$dispose', 'shutdownChecker']); | ||
@@ -1411,8 +1139,6 @@ _assert.default.deepEqual(Object.keys(dependencies), ['hash1', 'hash2', '$dispose', 'shutdownChecker']); | ||
}); | ||
yield dependencies.$dispose(); | ||
yield finalPromise; | ||
})); | ||
it('should delay service shutdown to their deeper dependencies', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
await dependencies.$dispose(); | ||
await finalPromise; | ||
}); | ||
it('should delay service shutdown to their deeper dependencies', async () => { | ||
const servicesShutdownCalls = _sinon.default.spy(() => Promise.resolve()); | ||
@@ -1432,13 +1158,11 @@ | ||
})))); | ||
const dependencies = yield $.run(['hash2', '$dispose']); | ||
const dependencies = await $.run(['hash2', '$dispose']); | ||
_assert.default.deepEqual(Object.keys(dependencies), ['hash2', '$dispose']); | ||
yield dependencies.$dispose(); | ||
await dependencies.$dispose(); | ||
_assert.default.deepEqual(servicesShutdownCalls.args, [['hash2'], ['hash1'], ['hash']]); | ||
})); | ||
it('should not shutdown singleton dependencies if used elsewhere', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should not shutdown singleton dependencies if used elsewhere', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1451,15 +1175,13 @@ $.register((0, _index.constant)('time', time)); | ||
hash | ||
} = yield $.run(['time', 'hash']); | ||
const dependencies = yield $.run(['time', 'hash', '$dispose']); | ||
} = await $.run(['time', 'hash']); | ||
const dependencies = await $.run(['time', 'hash', '$dispose']); | ||
_assert.default.equal(dependencies.hash, hash); | ||
yield dependencies.$dispose(); | ||
const newDependencies = yield $.run(['time', 'hash']); | ||
await dependencies.$dispose(); | ||
const newDependencies = await $.run(['time', 'hash']); | ||
_assert.default.equal(newDependencies.hash, hash); | ||
})); | ||
it('should shutdown singleton dependencies if not used elsewhere', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
}); | ||
it('should shutdown singleton dependencies if not used elsewhere', async () => { | ||
$.register((0, _index.constant)('ENV', ENV)); | ||
@@ -1473,8 +1195,8 @@ $.register((0, _index.constant)('time', time)); | ||
$dispose | ||
} = yield $.run(['time', 'hash', '$dispose']); | ||
yield $dispose(); | ||
const dependencies = yield $.run(['time', 'hash']); | ||
} = await $.run(['time', 'hash', '$dispose']); | ||
await $dispose(); | ||
const dependencies = await $.run(['time', 'hash']); | ||
_assert.default.notEqual(dependencies.hash, hash); | ||
})); | ||
}); | ||
}); | ||
@@ -1481,0 +1203,0 @@ describe('toMermaidGraph', () => { |
167
dist/util.js
@@ -9,2 +9,3 @@ "use strict"; | ||
exports.inject = inject; | ||
exports.autoInject = autoInject; | ||
exports.alsoInject = alsoInject; | ||
@@ -14,2 +15,3 @@ exports.extra = extra; | ||
exports.name = name; | ||
exports.autoName = autoName; | ||
exports.type = type; | ||
@@ -30,6 +32,2 @@ exports.initializer = initializer; | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
const debug = (0, _debug.default)('knifecycle'); | ||
@@ -116,14 +114,6 @@ /* Architecture Note #1.2: Creating initializers | ||
function wrapInitializer(wrapper, baseInitializer) { | ||
return reuseSpecialProps(baseInitializer, | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator(function* (services) { | ||
const baseInstance = yield baseInitializer(services); | ||
return wrapper(services, baseInstance); | ||
}); | ||
return function (_x) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}()); | ||
return reuseSpecialProps(baseInitializer, async services => { | ||
const baseInstance = await baseInitializer(services); | ||
return wrapper(services, baseInstance); | ||
}); | ||
} | ||
@@ -143,8 +133,12 @@ /** | ||
* | ||
* import { inject, getInstance } from 'knifecycle' | ||
* import Knifecycle, { inject } from 'knifecycle' | ||
* import myServiceInitializer from './service'; | ||
* | ||
* getInstance() | ||
* .service('myService', | ||
* inject(['ENV'], myServiceInitializer) | ||
* new Knifecycle() | ||
* .register( | ||
* service( | ||
* 'myService', | ||
* inject(['ENV'], myServiceInitializer) | ||
* ) | ||
* ) | ||
* ); | ||
@@ -166,2 +160,40 @@ */ | ||
/** | ||
* Decorator creating a new initializer with different | ||
* dependencies declarations set to it according to the | ||
* given function signature. | ||
* @param {Function} initializer | ||
* The original initializer | ||
* @return {Function} | ||
* Returns a new initializer | ||
* @example | ||
* | ||
* import Knifecycle, { autoInject, name } from 'knifecycle' | ||
* | ||
* new Knifecycle() | ||
* .register( | ||
* name( | ||
* 'application', | ||
* autoInject( | ||
* async ({ NODE_ENV, mysql: db }) => | ||
* async () => db.query('SELECT applicationId FROM applications WHERE environment=?', [NODE_ENV]) | ||
* ) | ||
* ) | ||
* ) | ||
* ) | ||
* ); | ||
*/ | ||
function autoInject(initializer) { | ||
const source = initializer.toString(); | ||
const matches = source.match(/\s*async\s+(?:function)?\s*\(\{\s*([^}]+)\s*\}\)/); | ||
if (!matches) { | ||
throw new _yerror.default('E_AUTO_INJECTION_FAILURE', source); | ||
} | ||
const dependenciesDeclarations = matches[1].trim().split(/\s*,\s*/).map(injection => injection.split(/\s*:\s*/).shift()); | ||
return inject(dependenciesDeclarations, initializer); | ||
} | ||
/** | ||
* Decorator creating a new initializer with some | ||
@@ -177,9 +209,9 @@ * more dependencies declarations appended to it. | ||
* | ||
* import { alsoInject, getInstance } from 'knifecycle' | ||
* import Knifecycle, { alsoInject } from 'knifecycle' | ||
* import myServiceInitializer from './service'; | ||
* | ||
* getInstance() | ||
* .service('myService', | ||
* new Knifecycle() | ||
* .register(service('myService', | ||
* alsoInject(['ENV'], myServiceInitializer) | ||
* ); | ||
* )); | ||
*/ | ||
@@ -208,9 +240,9 @@ | ||
* | ||
* import { extra, getInstance } from 'knifecycle' | ||
* import Knifecycle, { extra } from 'knifecycle' | ||
* import myServiceInitializer from './service'; | ||
* | ||
* getInstance() | ||
* .service('myService', | ||
* new Knifecycle() | ||
* .register(service('myService', | ||
* extra({ httpHandler: true }, myServiceInitializer) | ||
* ); | ||
* )); | ||
*/ | ||
@@ -241,11 +273,11 @@ | ||
* | ||
* import { inject, options, getInstance } from 'knifecycle'; | ||
* import Knifecycle, { inject, options } from 'knifecycle'; | ||
* import myServiceInitializer from './service'; | ||
* | ||
* getInstance() | ||
* .service('myService', | ||
* new Knifecycle() | ||
* .register(service('myService', | ||
* inject(['ENV'], | ||
* options({ singleton: true}, myServiceInitializer) | ||
* ) | ||
* ); | ||
* )); | ||
*/ | ||
@@ -271,6 +303,6 @@ | ||
* | ||
* import { name, getInstance } from 'knifecycle'; | ||
* import Knifecycle, { name } from 'knifecycle'; | ||
* import myServiceInitializer from './service'; | ||
* | ||
* getInstance() | ||
* new Knifecycle() | ||
* .register(name('myService', myServiceInitializer)); | ||
@@ -288,2 +320,26 @@ */ | ||
/** | ||
* Decorator to set an initializer name from its function name. | ||
* @param {Function} initializer | ||
* The initializer to name | ||
* @return {Function} | ||
* Returns a new initializer with that name set | ||
* @example | ||
* | ||
* import Knifecycle, { autoName } from 'knifecycle'; | ||
* | ||
* new Knifecycle() | ||
* .register(name(async function myService() {})); | ||
*/ | ||
function autoName(initializer) { | ||
const functionName = (initializer.name || '').split(' ').pop().replace(/^init(?:ialize)?([A-Z])/, (_, $1) => $1.toLowerCase()); | ||
if (!functionName) { | ||
throw new _yerror.default('E_AUTO_NAMING_FAILURE', initializer.name); | ||
} | ||
return name(functionName, initializer); | ||
} | ||
/** | ||
* Decorator to set an initializer type. | ||
@@ -298,6 +354,6 @@ * @param {String} type | ||
* | ||
* import { name, type, getInstance } from 'knifecycle'; | ||
* import Knifecycle, { name, type } from 'knifecycle'; | ||
* import myServiceInitializer from './service'; | ||
* | ||
* getInstance() | ||
* new Knifecycle() | ||
* .register( | ||
@@ -309,3 +365,3 @@ * type('service', | ||
* ) | ||
* ); | ||
* ); | ||
*/ | ||
@@ -331,6 +387,6 @@ | ||
* | ||
* import { initializer, getInstance } from 'knifecycle'; | ||
* import Knifecycle, { initializer } from 'knifecycle'; | ||
* import myServiceInitializer from './service'; | ||
* | ||
* getInstance() | ||
* new Knifecycle() | ||
* .register(initializer({ | ||
@@ -368,3 +424,3 @@ * name: 'myService', | ||
* @example | ||
* import { Knifecycle, constant, service } from 'knifecycle'; | ||
* import Knifecycle, { constant, service } from 'knifecycle'; | ||
* | ||
@@ -416,3 +472,3 @@ * const { printAnswer } = new Knifecycle() | ||
* @example | ||
* import { Knifecycle, constant, service } from 'knifecycle'; | ||
* import Knifecycle, { constant, service } from 'knifecycle'; | ||
* | ||
@@ -455,3 +511,3 @@ * const { printAnswer } = new Knifecycle() | ||
* | ||
* import Knifecycle from 'knifecycle' | ||
* import Knifecycle, { provider } from 'knifecycle' | ||
* import fs from 'fs'; | ||
@@ -497,4 +553,4 @@ * | ||
function deliverConstantValue(_x2) { | ||
return _deliverConstantValue.apply(this, arguments); | ||
async function deliverConstantValue(value) { | ||
return value; | ||
} | ||
@@ -512,5 +568,5 @@ /** | ||
* @example | ||
* import { initializer, getInstance } from 'knifecycle'; | ||
* import Knifecycle, { initializer } from 'knifecycle'; | ||
* | ||
* getInstance() | ||
* new Knifecycle() | ||
* .register(handler(getUser, ['db', '?log'])); | ||
@@ -527,9 +583,2 @@ * | ||
function _deliverConstantValue() { | ||
_deliverConstantValue = _asyncToGenerator(function* (value) { | ||
return value; | ||
}); | ||
return _deliverConstantValue.apply(this, arguments); | ||
} | ||
function handler(handlerFunction, dependencies = [], extra) { | ||
@@ -545,13 +594,3 @@ if (!handlerFunction.name) { | ||
extra | ||
}, | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref2 = _asyncToGenerator(function* (...args) { | ||
return handlerFunction.bind(null, ...args); | ||
}); | ||
return function () { | ||
return _ref2.apply(this, arguments); | ||
}; | ||
}()); | ||
}, async (...args) => handlerFunction.bind(null, ...args)); | ||
} | ||
@@ -558,0 +597,0 @@ /* Architecture Note #1.2.1: Dependencies declaration syntax |
@@ -11,6 +11,2 @@ "use strict"; | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
function aProvider() {} | ||
@@ -87,5 +83,3 @@ | ||
describe('wrapInitializer', () => { | ||
it('should work', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
it('should work', async () => { | ||
function baseInitializer() { | ||
@@ -113,3 +107,3 @@ return Promise.resolve(() => 'test'); | ||
}, baseInitializer); | ||
const service = yield newInitializer({ | ||
const service = await newInitializer({ | ||
log | ||
@@ -121,3 +115,3 @@ }); | ||
_assert.default.deepEqual(log.args, [['Wrapping...']]); | ||
})); | ||
}); | ||
}); | ||
@@ -146,2 +140,27 @@ describe('inject', () => { | ||
}); | ||
describe('autoInject', () => { | ||
it('should allow to decorate an initializer with dependencies', () => { | ||
const baseProvider = async ({ | ||
ENV, | ||
mysql: db | ||
}) => async () => ({ | ||
ENV, | ||
db | ||
}); | ||
const dependencies = ['ENV', 'mysql']; | ||
const newInitializer = (0, _util.autoInject)(baseProvider); | ||
_assert.default.notEqual(newInitializer, baseProvider); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
}); | ||
it('should fail with no injections', () => { | ||
_assert.default.throws(() => { | ||
(0, _util.autoInject)(async () => {}); | ||
}, /E_AUTO_INJECTION_FAILURE/); | ||
}); | ||
}); | ||
describe('alsoInject', () => { | ||
@@ -197,2 +216,89 @@ it('should allow to decorate an initializer with dependencies', () => { | ||
}); | ||
describe('autoName', () => { | ||
it('should allow to decorate an initializer with its function name', () => { | ||
const dependencies = ['ANOTHER_ENV>ENV']; | ||
const baseOptions = { | ||
singleton: true | ||
}; | ||
const baseName = 'hash'; | ||
const newInitializer = (0, _util.inject)(dependencies, (0, _util.options)(baseOptions, (0, _util.autoName)(async function hash() {}))); | ||
_assert.default.notEqual(newInitializer, aProvider); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.equal(newInitializer[_util.SPECIAL_PROPS.NAME], baseName); | ||
}); | ||
it('should allow to decorate an initializer with its init like function name', () => { | ||
const dependencies = ['ANOTHER_ENV>ENV']; | ||
const baseOptions = { | ||
singleton: true | ||
}; | ||
const baseName = 'hash'; | ||
const newInitializer = (0, _util.inject)(dependencies, (0, _util.options)(baseOptions, (0, _util.autoName)(async function initHash() {}))); | ||
_assert.default.notEqual(newInitializer, aProvider); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.equal(newInitializer[_util.SPECIAL_PROPS.NAME], baseName); | ||
}); | ||
it('should allow to decorate an initializer with its initialize like function name', () => { | ||
const dependencies = ['ANOTHER_ENV>ENV']; | ||
const baseOptions = { | ||
singleton: true | ||
}; | ||
const baseName = 'hash'; | ||
const newInitializer = (0, _util.inject)(dependencies, (0, _util.options)(baseOptions, (0, _util.autoName)(async function initializeHash() {}))); | ||
_assert.default.notEqual(newInitializer, aProvider); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.equal(newInitializer[_util.SPECIAL_PROPS.NAME], baseName); | ||
}); | ||
it('should allow to decorate a bounded initializer', () => { | ||
const dependencies = ['ANOTHER_ENV>ENV']; | ||
const baseOptions = { | ||
singleton: true | ||
}; | ||
const baseName = 'hash'; | ||
const newInitializer = (0, _util.autoName)((0, _util.inject)(dependencies, (0, _util.options)(baseOptions, async function initializeHash() {}))); | ||
_assert.default.notEqual(newInitializer, aProvider); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.INJECT], dependencies); | ||
_assert.default.notEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.deepEqual(newInitializer[_util.SPECIAL_PROPS.OPTIONS], baseOptions); | ||
_assert.default.equal(newInitializer[_util.SPECIAL_PROPS.NAME], baseName); | ||
}); | ||
it('should fail with anonymous functions', () => { | ||
_assert.default.throws(() => { | ||
(0, _util.autoName)(async () => {}); | ||
}, /E_AUTO_NAMING_FAILURE/); | ||
}); | ||
}); | ||
describe('extra', () => { | ||
@@ -268,5 +374,3 @@ it('should allow to decorate an initializer with extra infos', () => { | ||
describe('constant', () => { | ||
it('should allow to create an initializer from a constant', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
it('should allow to create an initializer from a constant', async () => { | ||
const baseValue = 'THE_VALUE'; | ||
@@ -290,9 +394,7 @@ const baseName = 42; | ||
_assert.default.equal((yield newInitializer()), baseValue); | ||
})); | ||
_assert.default.equal((await newInitializer()), baseValue); | ||
}); | ||
it('should fail with dependencies since it makes no sense', () => { | ||
_assert.default.throws(() => { | ||
(0, _util.constant)('time', (0, _util.inject)(['hash3'], | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () {}))); | ||
(0, _util.constant)('time', (0, _util.inject)(['hash3'], async () => {})); | ||
}, /E_CONSTANT_INJECTION/); | ||
@@ -302,15 +404,5 @@ }); | ||
describe('service', () => { | ||
it('should allow to create an initializer from a service builder', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
const aServiceBuilder = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref5 = _asyncToGenerator(function* () {}); | ||
it('should allow to create an initializer from a service builder', async () => { | ||
const aServiceBuilder = async () => {}; | ||
return function aServiceBuilder() { | ||
return _ref5.apply(this, arguments); | ||
}; | ||
}(); | ||
const dependencies = ['ANOTHER_ENV>ENV']; | ||
@@ -337,8 +429,6 @@ const baseOptions = { | ||
_assert.default.equal(newInitializer[_util.SPECIAL_PROPS.TYPE], baseType); | ||
})); | ||
}); | ||
}); | ||
describe('handler', () => { | ||
it('should work', | ||
/*#__PURE__*/ | ||
_asyncToGenerator(function* () { | ||
it('should work', async () => { | ||
const injectedServices = ['kikooo', 'lol']; | ||
@@ -355,4 +445,4 @@ const services = { | ||
const theHandler = yield theInitializer(services); | ||
const result = yield theHandler('test'); | ||
const theHandler = await theInitializer(services); | ||
const result = await theHandler('test'); | ||
@@ -370,3 +460,3 @@ _assert.default.deepEqual(result, { | ||
} | ||
})); | ||
}); | ||
it('should fail for anonymous functions', () => { | ||
@@ -373,0 +463,0 @@ _assert.default.throws(() => { |
{ | ||
"name": "knifecycle", | ||
"version": "3.1.0", | ||
"version": "4.0.0", | ||
"description": "Manage your NodeJS processes's lifecycle.", | ||
"main": "dist/index.js", | ||
"engines": { | ||
"node": ">=6.9.5" | ||
"node": ">=8.12.0" | ||
}, | ||
@@ -13,3 +13,2 @@ "metapak": { | ||
"readme", | ||
"mocha", | ||
"eslint", | ||
@@ -19,2 +18,3 @@ "travis", | ||
"babel", | ||
"mocha", | ||
"karma", | ||
@@ -29,2 +29,5 @@ "jsdocs", | ||
"dist" | ||
], | ||
"bundleFiles": [ | ||
"dist/**/*.js" | ||
] | ||
@@ -34,22 +37,24 @@ } | ||
"files": [ | ||
"dist", | ||
"src" | ||
"dist/**/*.js", | ||
"LICENSE", | ||
"README.md", | ||
"CHANGELOG.md" | ||
], | ||
"scripts": { | ||
"architecture": "jsarch src/*.js > ARCHITECTURE.md", | ||
"architecture": "jsarch src/*.js > ARCHITECTURE.md && git add ARCHITECTURE.md", | ||
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", | ||
"cli": "env NODE_ENV=${NODE_ENV:-cli}", | ||
"compile": "babel src --out-dir=dist", | ||
"cover": "nyc npm test && nyc report --reporter=text", | ||
"cover": "nyc npm test && nyc report --reporter=html --reporter=text", | ||
"coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls && rm -rf ./coverage", | ||
"cz": "env NODE_ENV=${NODE_ENV:-cli} git cz", | ||
"doc": "echo \"# API\" > API.md; jsdoc2md src/*.js >> API.md", | ||
"doc": "echo \"# API\" > API.md; jsdoc2md src/*.js >> API.md && git add API.md", | ||
"karma": "karma start karma.conf.js", | ||
"lint": "eslint src/*.js", | ||
"metapak": "metapak", | ||
"mocha": "mocha --compilers js:@babel/register src/*.mocha.js", | ||
"precz": "npm t && npm run lint && npm run metapak -- -s", | ||
"mocha": "mocha --require '@babel/register' src/*.mocha.js", | ||
"precz": "npm t && npm run lint && npm run doc && npm run architecture && npm run metapak -- -s", | ||
"prepublish": "npm run compile", | ||
"prettier": "prettier --write src/*.js", | ||
"preversion": "npm run compile && npm t && npm run lint && npm run metapak -- -s", | ||
"preversion": "npm run compile && npm t && npm run lint && npm run doc && npm run architecture && npm run metapak -- -s", | ||
"test": "npm run mocha && npm run karma", | ||
@@ -71,15 +76,15 @@ "version": "npm run changelog && git add CHANGELOG.md" | ||
"devDependencies": { | ||
"@babel/cli": "^7.0.0", | ||
"@babel/core": "^7.0.1", | ||
"@babel/cli": "^7.1.2", | ||
"@babel/core": "^7.1.2", | ||
"@babel/plugin-proposal-object-rest-spread": "^7.0.0", | ||
"@babel/preset-env": "^7.0.0", | ||
"@babel/preset-env": "^7.1.0", | ||
"@babel/register": "^7.0.0", | ||
"babel-eslint": "^9.0.0", | ||
"babel-eslint": "^10.0.1", | ||
"browserify": "^16.2.2", | ||
"commitizen": "^2.10.1", | ||
"conventional-changelog-cli": "^2.0.5", | ||
"commitizen": "^3.0.4", | ||
"conventional-changelog-cli": "^2.0.11", | ||
"coveralls": "^3.0.2", | ||
"cz-conventional-changelog": "^2.1.0", | ||
"eslint": "^5.6.0", | ||
"eslint-plugin-prettier": "^2.6.2", | ||
"eslint": "^5.8.0", | ||
"eslint-plugin-prettier": "^3.0.0", | ||
"jsarch": "^1.3.0", | ||
@@ -93,11 +98,11 @@ "jsdoc-to-markdown": "^4.0.1", | ||
"karma-sauce-launcher": "^1.2.0", | ||
"metapak": "^1.0.3", | ||
"metapak-nfroidure": "^7.1.1", | ||
"metapak": "^2.0.0", | ||
"metapak-nfroidure": "9.0.1", | ||
"mocha": "^5.2.0", | ||
"nyc": "^13.0.1", | ||
"prettier": "^1.14.2", | ||
"sinon": "^6.3.3" | ||
"prettier": "^1.14.3", | ||
"sinon": "^7.1.1" | ||
}, | ||
"dependencies": { | ||
"debug": "^4.0.1", | ||
"debug": "^4.1.0", | ||
"yerror": "^2.1.3" | ||
@@ -115,8 +120,8 @@ }, | ||
"conventional-changelog-cli", | ||
"eslint", | ||
"eslint-config-prettier", | ||
"prettier", | ||
"mocha", | ||
"coveralls", | ||
"nyc", | ||
"eslint", | ||
"eslint-config-prettier", | ||
"prettier", | ||
"karma", | ||
@@ -130,2 +135,30 @@ "karma-chrome-launcher", | ||
}, | ||
"contributors": [], | ||
"eslintConfig": { | ||
"extends": "eslint:recommended", | ||
"parserOptions": { | ||
"ecmaVersion": 2018, | ||
"sourceType": "module", | ||
"modules": true | ||
}, | ||
"env": { | ||
"es6": true, | ||
"node": true, | ||
"jest": true, | ||
"mocha": true | ||
}, | ||
"plugins": [ | ||
"prettier" | ||
], | ||
"rules": { | ||
"prettier/prettier": "error" | ||
} | ||
}, | ||
"prettier": { | ||
"semi": true, | ||
"printWidth": 80, | ||
"singleQuote": true, | ||
"trailingComma": "all", | ||
"proseWrap": "always" | ||
}, | ||
"babel": { | ||
@@ -137,3 +170,3 @@ "presets": [ | ||
"targets": { | ||
"node": "6.9.5" | ||
"node": "8.12.0" | ||
} | ||
@@ -146,4 +179,3 @@ } | ||
] | ||
}, | ||
"contributors": [] | ||
} | ||
} |
136
README.md
@@ -10,10 +10,10 @@ [//]: # ( ) | ||
[![Build status](https://secure.travis-ci.org/nfroidure/knifecycle.svg)](https://travis-ci.org/nfroidure/knifecycle) | ||
[![Coverage Status](https://coveralls.io/repos/nfroidure/knifecycle/badge.svg?branch=master)](https://coveralls.io/r/nfroidure/knifecycle?branch=master) | ||
[![NPM version](https://badge.fury.io/js/knifecycle.svg)](https://npmjs.org/package/knifecycle) | ||
[![Build status](https://secure.travis-ci.org/nfroidure/knifecycle.svg)](https://travis-ci.org/nfroidure/knifecycle) | ||
[![Dependency Status](https://david-dm.org/nfroidure/knifecycle.svg)](https://david-dm.org/nfroidure/knifecycle) | ||
[![devDependency Status](https://david-dm.org/nfroidure/knifecycle/dev-status.svg)](https://david-dm.org/nfroidure/knifecycle#info=devDependencies) | ||
[![Coverage Status](https://coveralls.io/repos/nfroidure/knifecycle/badge.svg?branch=master)](https://coveralls.io/r/nfroidure/knifecycle?branch=master) | ||
[![Code Climate](https://codeclimate.com/github/nfroidure/knifecycle.svg)](https://codeclimate.com/github/nfroidure/knifecycle) | ||
[![Dependency Status](https://dependencyci.com/github/nfroidure/knifecycle/badge)](https://dependencyci.com/github/nfroidure/knifecycle) | ||
[![Package Quality](http://npm.packagequality.com/shield/knifecycle.svg)](http://packagequality.com/#?package=knifecycle) | ||
[![Code Climate](https://codeclimate.com/github/nfroidure/knifecycle.svg)](https://codeclimate.com/github/nfroidure/knifecycle) | ||
@@ -50,3 +50,3 @@ | ||
make a definitive choice and allow both approaches. See | ||
[this Stack Overflow anser](http://stackoverflow.com/questions/9250851/do-i-need-dependency-injection-in-nodejs-or-how-to-deal-with/44084729#44084729) | ||
[this StackOverflow answer](http://stackoverflow.com/questions/9250851/do-i-need-dependency-injection-in-nodejs-or-how-to-deal-with/44084729#44084729) | ||
for more context about this statement. | ||
@@ -378,2 +378,7 @@ | ||
</dd> | ||
<dt><a href="#autoInject">autoInject(initializer)</a> ⇒ <code>function</code></dt> | ||
<dd><p>Decorator creating a new initializer with different | ||
dependencies declarations set to it according to the | ||
given function signature.</p> | ||
</dd> | ||
<dt><a href="#alsoInject">alsoInject(dependenciesDeclarations, initializer)</a> ⇒ <code>function</code></dt> | ||
@@ -396,2 +401,5 @@ <dd><p>Decorator creating a new initializer with some | ||
</dd> | ||
<dt><a href="#autoName">autoName(initializer)</a> ⇒ <code>function</code></dt> | ||
<dd><p>Decorator to set an initializer name from its function name.</p> | ||
</dd> | ||
<dt><a href="#type">type(type, initializer)</a> ⇒ <code>function</code></dt> | ||
@@ -476,3 +484,3 @@ <dd><p>Decorator to set an initializer type.</p> | ||
```js | ||
import { Knifecycle, inject, constant, service } from 'knifecycle'; | ||
import Knifecycle, { inject, constant, service } from 'knifecycle'; | ||
import appInitializer from './app'; | ||
@@ -506,3 +514,3 @@ | ||
```js | ||
import Knifecycle from 'knifecycle' | ||
import Knifecycle, { constant } from 'knifecycle' | ||
@@ -519,3 +527,3 @@ const $ = new Knifecycle(); | ||
### knifecycle._getServiceDescriptor(siloContext, serviceName, options, serviceProvider) ⇒ <code>Promise</code> | ||
### knifecycle.\_getServiceDescriptor(siloContext, serviceName, options, serviceProvider) ⇒ <code>Promise</code> | ||
Initialize or return a service descriptor | ||
@@ -537,3 +545,3 @@ | ||
### knifecycle._initializeServiceDescriptor(siloContext, serviceName, options) ⇒ <code>Promise</code> | ||
### knifecycle.\_initializeServiceDescriptor(siloContext, serviceName, options) ⇒ <code>Promise</code> | ||
Initialize a service descriptor | ||
@@ -554,3 +562,3 @@ | ||
### knifecycle._initializeDependencies(siloContext, serviceName, servicesDeclarations, options) ⇒ <code>Promise</code> | ||
### knifecycle.\_initializeDependencies(siloContext, serviceName, servicesDeclarations, options) ⇒ <code>Promise</code> | ||
Initialize a service dependencies | ||
@@ -658,10 +666,45 @@ | ||
```js | ||
import { inject, getInstance } from 'knifecycle' | ||
import Knifecycle, { inject } from 'knifecycle' | ||
import myServiceInitializer from './service'; | ||
getInstance() | ||
.service('myService', | ||
inject(['ENV'], myServiceInitializer) | ||
new Knifecycle() | ||
.register( | ||
service( | ||
'myService', | ||
inject(['ENV'], myServiceInitializer) | ||
) | ||
) | ||
); | ||
``` | ||
<a name="autoInject"></a> | ||
## autoInject(initializer) ⇒ <code>function</code> | ||
Decorator creating a new initializer with different | ||
dependencies declarations set to it according to the | ||
given function signature. | ||
**Kind**: global function | ||
**Returns**: <code>function</code> - Returns a new initializer | ||
| Param | Type | Description | | ||
| --- | --- | --- | | ||
| initializer | <code>function</code> | The original initializer | | ||
**Example** | ||
```js | ||
import Knifecycle, { autoInject, name } from 'knifecycle' | ||
new Knifecycle() | ||
.register( | ||
name( | ||
'application', | ||
autoInject( | ||
async ({ NODE_ENV, mysql: db }) => | ||
async () => db.query('SELECT applicationId FROM applications WHERE environment=?', [NODE_ENV]) | ||
) | ||
) | ||
) | ||
) | ||
); | ||
``` | ||
<a name="alsoInject"></a> | ||
@@ -683,9 +726,9 @@ | ||
```js | ||
import { alsoInject, getInstance } from 'knifecycle' | ||
import Knifecycle, { alsoInject } from 'knifecycle' | ||
import myServiceInitializer from './service'; | ||
getInstance() | ||
.service('myService', | ||
new Knifecycle() | ||
.register(service('myService', | ||
alsoInject(['ENV'], myServiceInitializer) | ||
); | ||
)); | ||
``` | ||
@@ -712,9 +755,9 @@ <a name="extra"></a> | ||
```js | ||
import { extra, getInstance } from 'knifecycle' | ||
import Knifecycle, { extra } from 'knifecycle' | ||
import myServiceInitializer from './service'; | ||
getInstance() | ||
.service('myService', | ||
new Knifecycle() | ||
.register(service('myService', | ||
extra({ httpHandler: true }, myServiceInitializer) | ||
); | ||
)); | ||
``` | ||
@@ -738,11 +781,11 @@ <a name="options"></a> | ||
```js | ||
import { inject, options, getInstance } from 'knifecycle'; | ||
import Knifecycle, { inject, options } from 'knifecycle'; | ||
import myServiceInitializer from './service'; | ||
getInstance() | ||
.service('myService', | ||
new Knifecycle() | ||
.register(service('myService', | ||
inject(['ENV'], | ||
options({ singleton: true}, myServiceInitializer) | ||
) | ||
); | ||
)); | ||
``` | ||
@@ -764,8 +807,27 @@ <a name="name"></a> | ||
```js | ||
import { name, getInstance } from 'knifecycle'; | ||
import Knifecycle, { name } from 'knifecycle'; | ||
import myServiceInitializer from './service'; | ||
getInstance() | ||
new Knifecycle() | ||
.register(name('myService', myServiceInitializer)); | ||
``` | ||
<a name="autoName"></a> | ||
## autoName(initializer) ⇒ <code>function</code> | ||
Decorator to set an initializer name from its function name. | ||
**Kind**: global function | ||
**Returns**: <code>function</code> - Returns a new initializer with that name set | ||
| Param | Type | Description | | ||
| --- | --- | --- | | ||
| initializer | <code>function</code> | The initializer to name | | ||
**Example** | ||
```js | ||
import Knifecycle, { autoName } from 'knifecycle'; | ||
new Knifecycle() | ||
.register(name(async function myService() {})); | ||
``` | ||
<a name="type"></a> | ||
@@ -786,6 +848,6 @@ | ||
```js | ||
import { name, type, getInstance } from 'knifecycle'; | ||
import Knifecycle, { name, type } from 'knifecycle'; | ||
import myServiceInitializer from './service'; | ||
getInstance() | ||
new Knifecycle() | ||
.register( | ||
@@ -797,3 +859,3 @@ type('service', | ||
) | ||
); | ||
); | ||
``` | ||
@@ -815,6 +877,6 @@ <a name="initializer"></a> | ||
```js | ||
import { initializer, getInstance } from 'knifecycle'; | ||
import Knifecycle, { initializer } from 'knifecycle'; | ||
import myServiceInitializer from './service'; | ||
getInstance() | ||
new Knifecycle() | ||
.register(initializer({ | ||
@@ -842,3 +904,3 @@ name: 'myService', | ||
```js | ||
import { Knifecycle, constant, service } from 'knifecycle'; | ||
import Knifecycle, { constant, service } from 'knifecycle'; | ||
@@ -874,3 +936,3 @@ const { printAnswer } = new Knifecycle() | ||
```js | ||
import { Knifecycle, constant, service } from 'knifecycle'; | ||
import Knifecycle, { constant, service } from 'knifecycle'; | ||
@@ -906,3 +968,3 @@ const { printAnswer } = new Knifecycle() | ||
```js | ||
import Knifecycle from 'knifecycle' | ||
import Knifecycle, { provider } from 'knifecycle' | ||
import fs from 'fs'; | ||
@@ -952,5 +1014,5 @@ | ||
```js | ||
import { initializer, getInstance } from 'knifecycle'; | ||
import Knifecycle, { initializer } from 'knifecycle'; | ||
getInstance() | ||
new Knifecycle() | ||
.register(handler(getUser, ['db', '?log'])); | ||
@@ -957,0 +1019,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1034
180862
12
3149
Updateddebug@^4.1.0