New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@midgar/midgar

Package Overview
Dependencies
Maintainers
1
Versions
62
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@midgar/midgar - npm Package Compare versions

Comparing version 1.0.0-aplha.3.0 to 1.0.0-aplha.3.1

tests/fixtures/services/test.service.js

4

package.json
{
"name": "@midgar/midgar",
"version": "1.0.0-aplha.3.0",
"version": "1.0.0-aplha.3.1",
"description": "node js framework",

@@ -53,2 +53,2 @@ "main": "./src/index.js",

"license": "MIT"
}
}

@@ -95,3 +95,2 @@ const Emittery = require('emittery')

/**

@@ -126,3 +125,3 @@ * Add a plugin definition

*
* @returns {PluginManager}
* @returns {Plugin}
*/

@@ -134,2 +133,48 @@ getPlugin (name) {

/**
* Add a service definition
*
* @param {ServiceDef} serviceDef Service definition
*
* @returns {void}
*/
addService (serviceDef) {
this.container.addService(serviceDef)
}
/**
* Add an array of service definition
*
* @param {Array<ServiceDef>} serviceDefs Service definitions
*
* @returns {void}
*/
addServices (serviceDefs) {
this.container.addServices(serviceDefs)
}
/**
* Add a directory of service
*
* @param {String} dirPath Directory path
* @param {String} pattern Glob pattern
*
* @returns {Promise<void>}
*/
async addServiceDir (dirPath, pattern) {
this.container.addServiceDir(dirPath, pattern)
}
/**
* Return a service instance
*
* @param {string} name Service name
*
* @returns {any}
*/
getService (name) {
return this.container.getService(name)
}
/**
* Return the node env code

@@ -162,6 +207,4 @@ *

async exit (code = 0) {
console.log('EXIT', code)
// Stop app
await this.stop()
console.log('STOP', code)

@@ -173,5 +216,3 @@ if (this.logger && !this._hasExitLogger) {

console.log('logger STOP', code)
// exit process
console.log('/EXIT', code)
process.exit(code)

@@ -187,3 +228,2 @@ }

// start exit sequence
console.log('_exitHandler exit')
return this.exit()

@@ -195,3 +235,2 @@ }

uncaughtExceptionHandler (error) {
console.log('uncaughtExceptionHandler', this._hasExitLogger)
if (this.logger && !this._hasExitLogger) {

@@ -210,3 +249,2 @@ // log exception

uncaughtRejectionHandler (error) {
console.log('uncaughtRejectionHandler', this._hasExitLogger)
if (this.logger && !this._hasExitLogger) {

@@ -213,0 +251,0 @@ // log exception

const path = require('path')
const { timer, isObject, asyncGlob } = require('./utils')
const { isObject, asyncGlob } = require('./utils')
/**
* @typedef {Object} ModuleDef
* @property {string} name Module name
* @property {constructor} module Module class
* @property {Array<string>} dependencies Dependencies module names
* @typedef {Object} ServiceDef
* @property {string} name Service name
* @property {constructor} service Service class
* @property {Array<string>} dependencies Dependencies service names
*/

@@ -16,244 +17,191 @@

module.exports = class Container {
/**
* @param {App} app App instance
*/
constructor (app) {
/**
* @param {App} app App instance
* App Instance
* @type {App}
*/
constructor (app) {
/**
* App Instance
* @type {App}
*/
this.app = app
this.app = app
/**
* Module définitions dictionnary
*/
this._moduleDefs = {}
/**
* Module instances définition
*/
this._moduleInstances = {}
}
/**
* Add a module définition
*
* @param {string} type Module type
* @param {ModuleDef} moduleDef Module définition
* @param {string} dependenciesType Default dependency type for DI
*
* @returns {void}
* Service définitions dictionnary
*/
addModule (type, moduleDef, dependenciesType = null) {
if (!dependenciesType) dependenciesType = type
this._serviceDefs = {}
moduleDef = { dependenciesType, ...moduleDef }
try {
this._checkModuleDef(moduleDef)
} catch (error) {
const moduleDefString = JSON.stringify(moduleDef, null, ' ')
throw new Error(`${error.message}\n${moduleDefString}`)
}
if (this._moduleDefs[type] === undefined) {
this._moduleDefs[type] = {}
}
this._moduleDefs[type][moduleDef.name] = moduleDef
}
/**
* Check a module definition and throw an Error
* if somthing wrong
*
* @param {ModuleDef} moduleDef Module définition
*
* @private
* Service instances dictionnary
*/
_checkModuleDef (moduleDef) {
if (typeof moduleDef !== 'object') throw new TypeError(`Invalid module définition type !`)
if (moduleDef.module === undefined) throw new Error(`No module propertie in module définition !`)
if (moduleDef.name === undefined) throw new Error(`No name propertie in module définition !`)
this._instances = {}
}
if (typeof moduleDef.name !== 'string') throw new TypeError(`Invalid module name type !`)
if (typeof moduleDef.dependenciesType !== 'string') throw new Error(`Invalid dependenciesType type in module définition !`)
/**
* Add a service définition
*
* @param {string} type Service type
* @param {ServiceDef} serviceDef Service définition
*
* @returns {void}
*/
addService (serviceDef) {
try {
this._checkServiceDef(serviceDef)
} catch (error) {
const serviceDefString = JSON.stringify(serviceDef, null, ' ')
throw new Error(`${error.message}\n${serviceDefString}`)
}
this._serviceDefs[serviceDef.name] = serviceDef
}
if (typeof moduleDef.module !== 'function')
throw new TypeError(`Invalid module type !`)
/**
* Check a service definition and throw an Error
* if somthing wrong
*
* @param {ServiceDef} serviceDef Service définition
*
* @private
*/
_checkServiceDef (serviceDef) {
if (typeof serviceDef !== 'object') throw new TypeError(`Invalid service définition type !`)
if (serviceDef.service === undefined) throw new Error(`No service propertie in service définition !`)
if (serviceDef.name === undefined) throw new Error(`No name propertie in service définition !`)
if (moduleDef.dependencies === undefined) return
if (typeof serviceDef.name !== 'string') throw new TypeError(`Invalid service name type !`)
if (!Array.isArray(moduleDef.dependencies))
throw new TypeError(`Invalid dependencies type !`)
for (const dependency of moduleDef.dependencies) {
if (isObject(dependency)) {
if (dependency.name === undefined) throw new Error(`No name propertie in module dependency !`)
if (typeof dependency.name !== 'string') throw new TypeError(`Invalid name type in module dependency !`)
if (dependency.type === undefined) throw new Error(`No type propertie in module dependency !`)
if (typeof dependency.type !== 'string') throw new TypeError(`Invalid type type in module dependency !`)
} else if (typeof dependency !== 'string') {
throw new TypeError(`Invalid module dependency type !`)
}
}
}
if (typeof serviceDef.service !== 'function')
throw new TypeError(`Invalid service type !`)
/**
* Add a directory of module
*
* Load all module in the dirPath with the glob pattern
*
* @param {String} type Module type
* @param {String} dirPath Directory path
* @param {String} pattern Glob pattern
* @param {string} defaultDependenciesType Default dependency type for DI
*
* @returns {Promise<void>}
*/
async addModuleDir (type, dirPath, pattern, dependenciesType = null) {
if (dependenciesType === null) dependenciesType = type
const moduleFiles = await asyncGlob(dirPath, pattern)
if (serviceDef.dependencies === undefined) return
for (const fileName of moduleFiles) {
const moduleDef = require(path.join(dirPath, fileName))
this.addModule(type, moduleDef, dependenciesType)
}
}
if (!Array.isArray(serviceDef.dependencies))
throw new TypeError(`Invalid service dependencies type !`)
/**
* Instanciate all module
*
* @param {String} type Module type
*
* @returns {void}
*/
intanciateModules (type) {
if (this._moduleDefs[type] !== undefined) {
for (const name in this._moduleDefs[type]) {
this.getModule(type, name)
}
}
for (const dependency of serviceDef.dependencies) {
if (typeof dependency !== 'string')
throw new TypeError(`Invalid service dependency type !`)
}
}
/**
* Return module instances
*
* @param {string} type Module type
*/
getInstances (type) {
return this._moduleInstances[type] ? this._moduleInstances[type] : []
}
/**
* Add a directory of service
*
* Load all service in the dirPath with the glob pattern
*
* @param {String} dirPath Directory path
* @param {String} pattern Glob pattern
*
* @returns {Promise<void>}
*/
async addServiceDir (dirPath, pattern) {
const serviceFiles = await asyncGlob(dirPath, pattern)
/**
* Return an instance of a module
*
* @param {string} type Module type
* @param {string} name Module name
*
* @returns {any}
*/
getModule (type, name) {
return this._getModule(type, name)
for (const fileName of serviceFiles) {
const serviceDef = require(path.join(dirPath, fileName))
this.addService(serviceDef)
}
}
/**
* Return an instance of a module
*
* @param {string} type Module type
* @param {string} name Module name
* @param {array} parents Array of parents modules
*
* @private
* @returns {any}
*/
_getModule (type, name, parents = []) {
if (this._moduleInstances[type] === undefined) this._moduleInstances[type] = {}
if (this._moduleInstances[type][name] === undefined) {
this._moduleInstances[type][name] = this._createModuleInstance(type, name, parents)
}
/**
* Return an instance of a service
*
* @param {string} name Service name
*
* @returns {any}
*/
getService (name) {
return this._getService(name)
}
return this._moduleInstances[type][name]
/**
* Return an instance of a service
*
* @param {string} name Service name
* @param {array} parents Array of parents services
*
* @private
* @returns {any}
*/
_getService (name, parents = []) {
if (this._instances[name] === undefined) {
this._instances[name] = this._createServiceInstance(name, parents)
}
/**
* Create an instance of a module
*
* @param {string} type Module type
* @param {string} name Module name
* @param {array} parents Array of parents modules
*
* @private
* @returns {any}
*/
_createModuleInstance (type, name, parents = []) {
if (this._moduleDefs[type] === undefined || this._moduleDefs[type][name] === undefined) {
throw new Error(`Unknow module ${name} of type ${type}.`)
}
return this._instances[name]
}
const timeKey = `module-${type}-${name}-init`
timer.start(timeKey)
/**
* Create an instance of a service
*
* @param {string} name Service name
* @param {array} parents Array of parents services
*
* @private
* @returns {any}
*/
_createServiceInstance (name, parents = []) {
if (this._serviceDefs[name] === undefined)
throw new Error(`Container: unknow service ${name}.`)
parents.push(type + ':' + name)
parents.push(name)
const moduleDef = this._moduleDefs[type][name]
let instance
let dependencies = []
if (moduleDef.dependencies && moduleDef.dependencies.length) {
dependencies = this._getModuleDependencies(type, moduleDef, parents)
}
const serviceDef = this._serviceDefs[name]
let instance
let dependencies = []
if (serviceDef.dependencies && serviceDef.dependencies.length) {
dependencies = this._getServiceDependencies(serviceDef, parents)
}
const args = [this.app]
const args = [this.app]
args.push(...dependencies)
// If the service is a class
if (/^class\s/.test(Function.prototype.toString.call(moduleDef.module))) {
const Class = moduleDef.module
instance = new Class(...args)
} else {
instance = moduleDef.module(...args)
}
args.push(...dependencies)
const time = timer.getTime(timeKey)
this.app.debug(`Create module ${type} instance ${name} in ${time} ms.`)
this.app.debug(`Container: create service instance ${name}.`)
return instance
// If the service is a class
if (/^class\s/.test(Function.prototype.toString.call(serviceDef.service))) {
const Class = serviceDef.service
instance = new Class(...args)
} else {
instance = serviceDef.service(...args)
}
/**
* Retrun an array of dependencies instance
*
* @param {string} moduleType Parent module type
* @param {string} moduleDef Parent module name
* @param {array} parents Array of parents modules
*
* @private
* @returns {Array<any>}
*/
_getModuleDependencies (moduleType, moduleDef, parents) {
const depependencies = []
for (const dependency of moduleDef.dependencies) {
return instance
}
let type = moduleDef.dependenciesType
let name
if (isObject(dependency)) {
type = dependency.type
name = dependency.name
} else if (typeof dependency === 'string') {
name = dependency
}
/**
* Retrun an array of dependencies instance
*
* @param {string} serviceDef Parent service name
* @param {array} parents Array of parents services
*
* @private
* @returns {Array<any>}
*/
_getServiceDependencies (serviceDef, parents) {
const depependencies = []
for (const dependency of serviceDef.dependencies) {
if (parents.indexOf(type + ':' + name) !== -1) {
throw new Error(
`Circular dependency in module ${moduleType}:${moduleDef.name}, ${type}:${name} already depend on ${moduleType}:${moduleDef.name} (${parents.join('->')})!`
)
}
let name
if (isObject(dependency)) {
type = dependency.type
name = dependency.name
} else if (typeof dependency === 'string') {
name = dependency
}
depependencies.push(this._getModule(type, name, JSON.parse(JSON.stringify(parents))))
}
if (parents.indexOf(name) !== -1) {
throw new Error(
`Circular dependency in service ${serviceDef.name}, ${name} already depend on ${serviceDef.name} (${[...parents, name].join('->')})!`
)
}
return depependencies
depependencies.push(this._getService(name, JSON.parse(JSON.stringify(parents))))
}
return depependencies
}
}

@@ -17,3 +17,2 @@ const path = require('path')

app = new App()
console.log('NEW APP')
});

@@ -52,2 +51,5 @@

/**
* Test start app
*/
it('App start', async () => {

@@ -71,3 +73,3 @@ await app.init(path.join(__dirname, './fixtures/config'))

/**
* Test
* Test add plugin
*/

@@ -90,3 +92,5 @@ it('App addPlugin', async () => {

/**
* Test get plugin
*/
it('App getPlugin', async () => {

@@ -104,2 +108,40 @@ await app.init(path.join(__dirname, './fixtures/config'))

/**
* Test add service
*/
it('App addService', async () => {
await app.init(path.join(__dirname, './fixtures/config'))
let addedServiceDef = null
jest.spyOn(app.container, 'addService').mockImplementationOnce((serviceDef) => {
addedServiceDef = serviceDef
})
app.addService({
test: true
})
expect(addedServiceDef).not.toBeNull()
expect(addedServiceDef).toHaveProperty('test', true)
})
/**
* Test get service
*/
it('App getService', async () => {
await app.init(path.join(__dirname, './fixtures/config'))
jest.spyOn(app.container, 'getService').mockImplementationOnce((name) => {
return { test: name }
})
const service = app.getService('test-service')
expect(service).toHaveProperty('test', 'test-service')
})
/**
* Test getNodeEnv()
*/
it('App getNodeEnv', async () => {

@@ -113,2 +155,5 @@ delete process.env.NODE_ENV

/**
* Test exit
*/
it('App exit', async () => {

@@ -128,20 +173,20 @@ await app.init(path.join(__dirname, './fixtures/config'))

/**
* Test exit handler
*/
it('App exit handler', async () => {
await app.init(path.join(__dirname, './fixtures/config'))
console.log('App exit handler')
jest.spyOn(app, 'exit').mockImplementationOnce(() => {
console.log('Exit')
})
console.log('SIGUSR1 SIGUSR1 SIGUSR1 SIGUSR1')
await app.exitHandler()
expect(app.exit).toHaveBeenCalled();
console.log('/App exit handler')
})
/**
* Test uncaughtException
*/
it('App uncaughtException', async (done) => {
console.log('App uncaughtException')
await app.init(path.join(__dirname, './fixtures/config'))

@@ -154,11 +199,11 @@

expect(app.exit).toHaveBeenCalled();
console.log('/App uncaughtException')
done()
})
/**
* Test unhandledRejection
*/
it('App unhandledRejection', async (done) => {
await app.init(path.join(__dirname, './fixtures/config'))
console.log('App unhandledRejection')
jest.spyOn(app, 'exit').mockImplementationOnce(() => { })

@@ -169,3 +214,2 @@

expect(app.exit).toHaveBeenCalled();
console.log('App /unhandledRejection')

@@ -176,4 +220,6 @@ done()

/**
* Test stop
*/
it('App stop', async (done) => {
await app.init(path.join(__dirname, './fixtures/config'))

@@ -189,2 +235,5 @@ await app.start()

/**
* Test log methods
*/
it('App log', async (done) => {

@@ -191,0 +240,0 @@ await app.init(path.join(__dirname, './fixtures/config'))

const path = require('path')
const { Plugin } = require('../../src')
const App = require('../../src/app')
const testModulenDef = require('../fixtures/modules/test.module')
const test2ModulenDef = require('../fixtures/modules/test2.module')
const testServiceDef = require('../fixtures/services/test.service')
const test2ServiceDef = require('../fixtures/services/test2.service')

@@ -24,28 +23,23 @@ /**

})
/**
* Test unknow npm dependency error case
* Test addService
*/
it('Container addModule', async (done) => {
const type = 'test-type'
it('Container addService', async (done) => {
const name = 'test'
class TestModule {
class TestService {
}
expect(() => app.container.addModule(type, { name, module: TestModule, dependencies: [{ name: 'test2', type }, 'test3'] })).not.toThrow(Error)
expect(() => app.container.addModule(type, { name, module: () => { } })).not.toThrow(Error)
expect(() => app.container.addService({ name, service: () => { } })).not.toThrow(Error)
// Invalid module definition
expect(() => app.container.addModule(type, '{}')).toThrow(Error)
expect(() => app.container.addModule(type, {})).toThrow(Error)
expect(() => app.container.addModule(type, { name })).toThrow(Error)
expect(() => app.container.addModule(type, { module: TestModule })).toThrow(Error)
expect(() => app.container.addModule(type, { name: () => { }, module: TestModule })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: 'x' })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: TestModule, dependenciesType: 1 })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: TestModule, dependencies: 1 })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: TestModule, dependencies: [1] })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: TestModule, dependencies: [{}] })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: TestModule, dependencies: [{ name: 1, type: 'test' }] })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: TestModule, dependencies: [{ name: 'test' }] })).toThrow(Error)
expect(() => app.container.addModule(type, { name, module: TestModule, dependencies: [{ name: 'test', type: 1 }] })).toThrow(Error)
expect(() => app.container.addService('{}')).toThrow(Error)
expect(() => app.container.addService({})).toThrow(Error)
expect(() => app.container.addService({ name })).toThrow(Error)
expect(() => app.container.addService({ service: TestService })).toThrow(Error)
expect(() => app.container.addService({ name: () => { }, service: TestService })).toThrow(Error)
expect(() => app.container.addService({ name, service: 'x' })).toThrow(Error)
expect(() => app.container.addService({ name, service: TestService, dependencies: 1 })).toThrow(Error)
expect(() => app.container.addService({ name, service: TestService, dependencies: [1] })).toThrow(Error)
expect(() => app.container.addService({ name, service: TestService, dependencies: [{}] })).toThrow(Error)

@@ -56,7 +50,6 @@ done()

/**
* Test getModule method
* Test getService method
*/
it('Container getModule', async (done) => {
const type = 'test-type'
class TestModule {
it('Container getService', async (done) => {
class TestService {
constructor (app) {

@@ -67,38 +60,37 @@ this.app = app

app.container.addModule(type, {
module: TestModule,
app.container.addService({
service: TestService,
name: 'test'
})
class Test2Module {
constructor (app, testModule, testFnModule) {
class Test2Service {
constructor (app, testService, testFnService) {
this.app = app
this.testModule = testModule
this.testFnModule = testFnModule
this.testService = testService
this.testFnService = testFnService
}
}
app.container.addModule(type, {
module: () => 'test-function-value',
app.container.addService({
service: () => 'test-function-value',
name: 'test-function',
})
app.container.addModule(type, {
module: Test2Module,
app.container.addService({
service: Test2Service,
name: 'test2',
dependencies: ['test', { type, name: 'test-function' }]
dependencies: ['test', 'test-function']
})
const testModule = app.container.getModule(type, 'test')
const testService = app.container.getService('test')
expect(testModule).toBeInstanceOf(TestModule)
expect(testModule.app).toBeInstanceOf(App)
expect(testService).toBeInstanceOf(TestService)
expect(testService.app).toBeInstanceOf(App)
const test2Module = app.container.getModule(type, 'test2')
expect(test2Module).toBeInstanceOf(Test2Module)
expect(test2Module.app).toBeInstanceOf(App)
expect(test2Module.testModule).toBeInstanceOf(TestModule)
expect(test2Module.testFnModule).toEqual('test-function-value')
const test2Service = app.container.getService('test2')
expect(test2Service).toBeInstanceOf(Test2Service)
expect(test2Service.app).toBeInstanceOf(App)
expect(test2Service.testService).toBeInstanceOf(TestService)
expect(test2Service.testFnService).toEqual('test-function-value')
expect(() => app.container.getModule(type, 'testx')).toThrow(Error)
expect(() => app.container.getModule('xxx', 'test')).toThrow(Error)
expect(() => app.container.getService('testx')).toThrow(Error)

@@ -108,3 +100,2 @@ done()

/**

@@ -116,4 +107,4 @@ * Test circular dependency

app.container.addModule(type, {
module: () => { },
app.container.addService({
service: () => { },
name: 'test',

@@ -123,4 +114,4 @@ dependencies: ['test2'],

app.container.addModule(type, {
module: () => { },
app.container.addService({
service: () => { },
name: 'test2',

@@ -130,8 +121,8 @@ dependencies: ['test3'],

app.container.addModule(type, {
module: () => { },
app.container.addService({
service: () => { },
name: 'test3',
dependencies: ['test'],
})
expect(() => app.container.getModule(type, 'test')).toThrow(Error)
expect(() => app.container.getService('test')).toThrow(Error)
done()

@@ -141,45 +132,12 @@ })

/**
* Test addModuleDir method
* Test addServiceDir method
*/
it('Container addModuleDir', async (done) => {
const type = 'test-type'
it('Container addServiceDir', async (done) => {
await app.container.addServiceDir(path.resolve(__dirname, '../fixtures/services'), '*.service.js')
await app.container.addModuleDir(type, path.resolve(__dirname, '../fixtures/modules'), '*.module.js')
expect(app.container.getModule(type, 'test')).toBeInstanceOf(testModulenDef.module)
expect(app.container.getModule(type, 'test2')).toBeInstanceOf(test2ModulenDef.module)
expect(app.container.getService('test')).toBeInstanceOf(testServiceDef.service)
expect(app.container.getService('test2')).toBeInstanceOf(test2ServiceDef.service)
done()
})
/**
* Test intanciateModules method
*/
it('Container intanciateModules', async (done) => {
const type = 'test-type'
class TestModule {
}
app.container.addModule(type, {
module: TestModule,
name: 'test'
})
class Test2Module {
}
app.container.addModule(type, {
module: Test2Module,
name: 'test2'
})
app.container.intanciateModules(type)
const instances = app.container.getInstances(type)
expect(Object.keys(instances).length).toEqual(2)
expect(instances['test']).toBeInstanceOf(TestModule)
expect(instances['test2']).toBeInstanceOf(Test2Module)
done()
})
})

@@ -44,3 +44,2 @@ const path = require('path')

console.log('test messageeeeeee')
const level = 'info'

@@ -50,3 +49,2 @@ const msg = 'test message'

console.log('/test messageeeeeee')
// Exit to wait write and close file

@@ -53,0 +51,0 @@ await logger.exit()

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc