Skip to content

Commit

Permalink
feat(core): App-level configuration method
Browse files Browse the repository at this point in the history
app.config will bind all first and second level properties for
retrieval via injection or .get methods
  • Loading branch information
Kevin Delisle committed Oct 2, 2017
1 parent 051b8e0 commit 8153f86
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/core/src/application.ts
Expand Up @@ -161,6 +161,36 @@ export class Application extends Context {
);
}

// tslint:disable-next-line:no-any
public config(cfg: {[key: string]: any}) {
for (const key in cfg) {
const item = cfg[key];
// Iterate through the keys one level down (not recursively!)
if (item instanceof Object) {
for (const subkey in item) {
this.bindItemOrClass(`${key}.${subkey}`, item[subkey]);
}
}
this.bindItemOrClass(key, item);
}
}
/**
* Helper function for either binding an item or a class, depending.
* @private
* @param key The key of the configuration element.
* @param itemOrClass The item or class to bind.
*/
// tslint:disable-next-line:no-any
private bindItemOrClass(key: string, itemOrClass: any) {
if (itemOrClass instanceof Function) {
this.bind(key)
.toClass(itemOrClass)
.inScope(BindingScope.SINGLETON);
} else {
this.bind(key).to(itemOrClass);
}
}

/**
* Add a component to this application.
*
Expand Down
26 changes: 26 additions & 0 deletions packages/core/test/unit/application.test.ts
Expand Up @@ -26,6 +26,32 @@ describe('Application', () => {
});

describe('configuration', () => {
it('allows bindings to be set via config method', async () => {
const app = new Application();
// tslint:disable-next-line:no-any
const samoflange: any = {
vertices: 'many',
usefulness: 0,
};
app.config({
magicCode: 'foobar',
servers: {
abc123: FakeServer,
},
CustomComponentCo: {
samoflange: samoflange,
},
});
const code = await app.get('magicCode');
const server = (await app.getServer('abc123')) as FakeServer;
expect(code).to.equal('foobar');
expect(server.constructor.name).to.equal(FakeServer.name);
const samo = await app.get(`CustomComponentCo.samoflange`);
for (const key in samo) {
expect(samo[key]).to.equal(samoflange[key]);
}
});

it('allows servers to be provided via config', async () => {
const name = 'abc123';
const app = new Application({
Expand Down

0 comments on commit 8153f86

Please sign in to comment.