Browse Source

Add separate proxy() method to container

tags/0.4.4
Garrett Mills 1 month ago
parent
commit
dba9fee204
Signed by: garrettmills <garrett@glmdev.tech> GPG Key ID: 6ACD58D6ADACFC6E
2 changed files with 23 additions and 7 deletions
  1. 9
    7
      src/Container.js
  2. 14
    0
      test/Container.spec.js

+ 9
- 7
src/Container.js View File

@@ -66,13 +66,7 @@ class Container {
* @returns {module:flitter-di/src/Service~Service|undefined} - the service instance or service container proxy
*/
service(service = false) {
if ( service === false ) {
return new Proxy({}, {
get: (obj, prop) => {
return this.service(prop)
}
})
}
if ( service === false ) return this.proxy()

if ( !this.definitions[service] ) {
throw new Error('No such service registered with this container: '+service)
@@ -95,6 +89,14 @@ class Container {
return this.instances[service]
}

proxy() {
return new Proxy({}, {
get: (what, name) => {
return this.service(name)
}
})
}

/**
* Register a class definition as a service. When requested, the service
* for this class will be created from the class' instance.

+ 14
- 0
test/Container.spec.js View File

@@ -129,6 +129,20 @@ describe('the inversion of control container', function() {
})
})

describe('proxy function', function() {
it('should return a proxy container that can resolve services', function() {
class TestService {}
const name = Math.random().toString(36).substring(7)
const defs = {}
defs[name] = TestService
const container = new Container(defs)
const services = container.proxy()

expect(util.types.isProxy(services)).to.be.true
expect(services[name]).to.be.an.instanceof(TestService)
})
})

describe('register function', function() {
it('should be a function', function() {
const container = new Container()

Loading…
Cancel
Save