Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(context): add support to sort bindings for @inject.* and ContextView #2848

Merged
merged 2 commits into from
May 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/site/Context.md
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,8 @@ should be able to pick up these new routes without restarting.
To support the dynamic tracking of such artifacts registered within a context
chain, we introduce `ContextObserver` interface and `ContextView` class that can
be used to watch a list of bindings matching certain criteria depicted by a
`BindingFilter` function.
`BindingFilter` function and an optional `BindingComparator` function to sort
matched bindings.

```ts
import {Context, ContextView} from '@loopback/context';
Expand Down
17 changes: 17 additions & 0 deletions docs/site/Decorators_inject.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,23 @@ class MyControllerWithValues {
}
```

To sort matched bindings found by the binding filter function, `@inject` honors
`bindingComparator` in `metadata`:

```ts
class MyControllerWithValues {
constructor(
@inject(binding => binding.tagNames.includes('foo'), {
bindingComparator: (a, b) => {
bajtos marked this conversation as resolved.
Show resolved Hide resolved
// Sort by value of `foo` tag
return a.tagMap.foo.localeCompare(b.tagMap.foo);
},
})
public values: string[],
) {}
}
```

A few variants of `@inject` are provided to declare special forms of
dependencies.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@
// License text available at https://opensource.org/licenses/MIT

import {expect} from '@loopback/testlab';
import {Context, ContextView, filterByTag, Getter, inject} from '../..';
import {
compareBindingsByTag,
Context,
ContextView,
filterByTag,
Getter,
inject,
} from '../..';

let app: Context;
let server: Context;
Expand All @@ -29,6 +36,26 @@ describe('@inject.* to receive multiple values matching a filter', async () => {
expect(await getter()).to.eql([3, 7, 5]);
});

it('injects as getter with bindingComparator', async () => {
class MyControllerWithGetter {
@inject.getter(workloadMonitorFilter, {
bindingComparator: compareBindingsByTag('name'),
})
getter: Getter<number[]>;
}

server.bind('my-controller').toClass(MyControllerWithGetter);
const inst = await server.get<MyControllerWithGetter>('my-controller');
const getter = inst.getter;
// app-reporter, server-reporter
expect(await getter()).to.eql([5, 3]);
// Add a new binding that matches the filter
givenWorkloadMonitor(server, 'server-reporter-2', 7);
// The getter picks up the new binding by order
// // app-reporter, server-reporter, server-reporter-2
expect(await getter()).to.eql([5, 3, 7]);
});

describe('@inject', () => {
class MyControllerWithValues {
constructor(
Expand All @@ -48,6 +75,37 @@ describe('@inject.* to receive multiple values matching a filter', async () => {
const inst = server.getSync<MyControllerWithValues>('my-controller');
expect(inst.values).to.eql([3, 5]);
});

it('injects as values with bindingComparator', async () => {
class MyControllerWithBindingSorter {
constructor(
@inject(workloadMonitorFilter, {
bindingComparator: compareBindingsByTag('name'),
})
public values: number[],
) {}
}
server.bind('my-controller').toClass(MyControllerWithBindingSorter);
const inst = await server.get<MyControllerWithBindingSorter>(
'my-controller',
);
// app-reporter, server-reporter
expect(inst.values).to.eql([5, 3]);
});

it('throws error if bindingComparator is provided without a filter', () => {
expect(() => {
// tslint:disable-next-line:no-unused
class ControllerWithInvalidInject {
constructor(
@inject('my-key', {
bindingComparator: compareBindingsByTag('name'),
})
public values: number[],
) {}
}
}).to.throw('Binding sorter is only allowed with a binding filter');
});
});

it('injects as a view', async () => {
Expand All @@ -68,6 +126,24 @@ describe('@inject.* to receive multiple values matching a filter', async () => {
expect(await view.values()).to.eql([3, 5]);
});

it('injects as a view with bindingComparator', async () => {
class MyControllerWithView {
@inject.view(workloadMonitorFilter, {
bindingComparator: compareBindingsByTag('name'),
})
view: ContextView<number[]>;
}

server.bind('my-controller').toClass(MyControllerWithView);
const inst = await server.get<MyControllerWithView>('my-controller');
const view = inst.view;
expect(view.bindings.map(b => b.tagMap.name)).to.eql([
'app-reporter',
'server-reporter',
]);
expect(await view.values()).to.eql([5, 3]);
});

function givenWorkloadMonitors() {
givenServerWithinAnApp();
givenWorkloadMonitor(server, 'server-reporter', 3);
Expand All @@ -84,7 +160,8 @@ describe('@inject.* to receive multiple values matching a filter', async () => {
return ctx
.bind(`workloadMonitors.${name}`)
.to(workload)
.tag('workloadMonitor');
.tag('workloadMonitor')
.tag({name});
}
});

Expand Down
155 changes: 155 additions & 0 deletions packages/context/src/__tests__/unit/binding-sorter.unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Copyright IBM Corp. 2019. All Rights Reserved.
// Node module: @loopback/context
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {expect} from '@loopback/testlab';
import {Binding, compareByOrder, sortBindingsByPhase} from '../..';

describe('BindingComparator', () => {
const FINAL = Symbol('final');
const orderOfPhases = ['log', 'auth', FINAL];
const phaseTagName = 'phase';
let bindings: Binding<unknown>[];
let sortedBindingKeys: string[];

beforeEach(givenBindings);
beforeEach(sortBindings);

it('sorts by phase', () => {
/**
* Phases
* - 'log': logger1, logger2
* - 'auth': auth1, auth2
*/
assertOrder('logger1', 'logger2', 'auth1', 'auth2');
});

it('sorts by phase - unknown phase comes before known ones', () => {
/**
* Phases
* - 'metrics': metrics // not part of ['log', 'auth']
* - 'log': logger1
*/
assertOrder('metrics', 'logger1');
raymondfeng marked this conversation as resolved.
Show resolved Hide resolved
});

it('sorts by phase alphabetically without orderOf phase', () => {
/**
* Phases
* - 'metrics': metrics // not part of ['log', 'auth']
* - 'rateLimit': rateLimit // not part of ['log', 'auth']
*/
assertOrder('metrics', 'rateLimit');
});

it('sorts by binding order without phase tags', () => {
/**
* Phases
* - '': validator1, validator2 // not part of ['log', 'auth']
* - 'metrics': metrics // not part of ['log', 'auth']
* - 'log': logger1
*/
assertOrder('validator1', 'validator2', 'metrics', 'logger1');
});

it('sorts by binding order without phase tags', () => {
/**
* Phases
* - '': validator1 // not part of ['log', 'auth']
* - 'metrics': metrics // not part of ['log', 'auth']
* - 'log': logger1
* - 'final': Symbol('final')
*/
assertOrder('validator1', 'metrics', 'logger1', 'final');
});

/**
* The sorted bindings by phase:
* - '': validator1, validator2 // not part of ['log', 'auth']
* - 'metrics': metrics // not part of ['log', 'auth']
* - 'rateLimit': rateLimit // not part of ['log', 'auth']
* - 'log': logger1, logger2
* - 'auth': auth1, auth2
*/
function givenBindings() {
bindings = [
Binding.bind('logger1').tag({[phaseTagName]: 'log'}),
Binding.bind('auth1').tag({[phaseTagName]: 'auth'}),
Binding.bind('auth2').tag({[phaseTagName]: 'auth'}),
Binding.bind('logger2').tag({[phaseTagName]: 'log'}),
Binding.bind('metrics').tag({[phaseTagName]: 'metrics'}),
Binding.bind('rateLimit').tag({[phaseTagName]: 'rateLimit'}),
Binding.bind('validator1'),
Binding.bind('validator2'),
Binding.bind('final').tag({[phaseTagName]: FINAL}),
];
}

function sortBindings() {
sortBindingsByPhase(bindings, phaseTagName, orderOfPhases);
sortedBindingKeys = bindings.map(b => b.key);
}

function assertOrder(...keys: string[]) {
let prev: number = -1;
let prevKey: string = '';
for (const key of keys) {
const current = sortedBindingKeys.indexOf(key);
expect(current).to.greaterThan(
prev,
`Binding ${key} should come after ${prevKey}`,
);
prev = current;
prevKey = key;
}
}
});

describe('compareByOrder', () => {
it('honors order', () => {
expect(compareByOrder('a', 'b', ['b', 'a'])).to.greaterThan(0);
});

it('value not included in order comes first', () => {
expect(compareByOrder('a', 'c', ['a', 'b'])).to.greaterThan(0);
});

it('values not included are compared alphabetically', () => {
expect(compareByOrder('a', 'c', [])).to.lessThan(0);
});

it('null/undefined/"" values are treated as ""', () => {
expect(compareByOrder('', 'c')).to.lessThan(0);
expect(compareByOrder(null, 'c')).to.lessThan(0);
expect(compareByOrder(undefined, 'c')).to.lessThan(0);
});

it('returns 0 for equal values', () => {
expect(compareByOrder('c', 'c')).to.equal(0);
expect(compareByOrder(null, '')).to.equal(0);
expect(compareByOrder('', undefined)).to.equal(0);
});

it('allows symbols', () => {
const a = Symbol('a');
const b = Symbol('b');
expect(compareByOrder(a, b)).to.lessThan(0);
expect(compareByOrder(a, b, [b, a])).to.greaterThan(0);
expect(compareByOrder(a, 'b', [b, a])).to.greaterThan(0);
});

it('list symbols before strings', () => {
const a = 'a';
const b = Symbol('a');
expect(compareByOrder(a, b)).to.greaterThan(0);
expect(compareByOrder(b, a)).to.lessThan(0);
});

it('compare symbols by description', () => {
const a = Symbol('a');
const b = Symbol('b');
expect(compareByOrder(a, b)).to.lessThan(0);
expect(compareByOrder(b, a)).to.greaterThan(0);
});
});
30 changes: 28 additions & 2 deletions packages/context/src/__tests__/unit/context-view.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {expect} from '@loopback/testlab';
import {
Binding,
BindingScope,
compareBindingsByTag,
Context,
ContextView,
createViewGetter,
Expand All @@ -26,6 +27,15 @@ describe('ContextView', () => {
expect(taggedAsFoo.bindings).to.eql(bindings);
});

it('sorts matched bindings', () => {
const view = new ContextView(
server,
filterByTag('foo'),
compareBindingsByTag('phase', ['b', 'a']),
);
expect(view.bindings).to.eql([bindings[1], bindings[0]]);
});

it('resolves bindings', async () => {
expect(await taggedAsFoo.resolve()).to.eql(['BAR', 'FOO']);
expect(await taggedAsFoo.values()).to.eql(['BAR', 'FOO']);
Expand Down Expand Up @@ -154,6 +164,22 @@ describe('ContextView', () => {
.tag('foo');
expect(await getter()).to.eql(['BAR', 'XYZ', 'FOO']);
});

it('creates a getter function for the binding filter and sorter', async () => {
const getter = createViewGetter(server, filterByTag('foo'), (a, b) => {
return a.key.localeCompare(b.key);
});
expect(await getter()).to.eql(['BAR', 'FOO']);
server
.bind('abc')
.to('ABC')
.tag('abc');
server
.bind('xyz')
.to('XYZ')
.tag('foo');
expect(await getter()).to.eql(['BAR', 'FOO', 'XYZ']);
});
});

function givenContextView() {
Expand All @@ -169,14 +195,14 @@ describe('ContextView', () => {
server
.bind('bar')
.toDynamicValue(() => Promise.resolve('BAR'))
.tag('foo', 'bar')
.tag('foo', 'bar', {phase: 'a'})
.inScope(BindingScope.SINGLETON),
);
bindings.push(
app
.bind('foo')
.to('FOO')
.tag('foo', 'bar'),
.tag('foo', 'bar', {phase: 'b'}),
);
}
});
Loading