Skip to content

feat(context): add type as a generic parameter to ctx.get() and friends #1050

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

Merged
merged 2 commits into from
Mar 1, 2018
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
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ describe('AuthenticationProvider', () => {
.bind(AuthenticationBindings.AUTH_ACTION)
.toProvider(AuthenticationProvider);
const request = <ParsedRequest>{};
const authenticate = await context.get(
const authenticate = await context.get<AuthenticateFn>(
AuthenticationBindings.AUTH_ACTION,
);
const user: UserProfile = await authenticate(request);
const user: UserProfile | undefined = await authenticate(request);
expect(user).to.be.equal(mockUser);
});

Expand All @@ -73,7 +73,7 @@ describe('AuthenticationProvider', () => {
context
.bind(AuthenticationBindings.AUTH_ACTION)
.toProvider(AuthenticationProvider);
const authenticate = await context.get(
const authenticate = await context.get<AuthenticateFn>(
AuthenticationBindings.AUTH_ACTION,
);
const request = <ParsedRequest>{};
Expand All @@ -92,7 +92,7 @@ describe('AuthenticationProvider', () => {
context
.bind(AuthenticationBindings.AUTH_ACTION)
.toProvider(AuthenticationProvider);
const authenticate = await context.get(
const authenticate = await context.get<AuthenticateFn>(
AuthenticationBindings.AUTH_ACTION,
);
const request = <ParsedRequest>{};
Expand Down
5 changes: 4 additions & 1 deletion packages/boot/src/bootstrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,10 @@ export class Bootstrapper {

// Resolve Booter Instances
const booterInsts = await resolveList(filteredBindings, binding =>
bootCtx.get(binding.key),
// We cannot use Booter interface here because "filter.booters"
// allows arbitrary string values, not only the phases defined
// by Booter interface
bootCtx.get<{[phase: string]: () => Promise<void>}>(binding.key),
);

// Run phases of booters
Expand Down
64 changes: 39 additions & 25 deletions packages/boot/test/unit/bootstrapper.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,49 +16,50 @@ describe('boot-strapper unit tests', () => {
let app: BootApp;
let bootstrapper: Bootstrapper;
const booterKey = `${BootBindings.BOOTER_PREFIX}.TestBooter`;
const booterKey2 = `${BootBindings.BOOTER_PREFIX}.TestBooter2`;
const anotherBooterKey = `${BootBindings.BOOTER_PREFIX}.AnotherBooter`;

beforeEach(getApplication);
beforeEach(getBootStrapper);

it('finds and runs registered booters', async () => {
const ctx = await bootstrapper.boot();
const booterInst = await ctx.get(booterKey);
expect(booterInst.configureCalled).to.be.True();
expect(booterInst.loadCalled).to.be.True();
const booterInst = await ctx.get<TestBooter>(booterKey);
expect(booterInst.phasesCalled).to.eql([
'TestBooter:configure',
'TestBooter:load',
]);
});

it('binds booters passed in BootExecutionOptions', async () => {
const ctx = await bootstrapper.boot({booters: [TestBooter2]});
const booterInst2 = await ctx.get(booterKey2);
expect(booterInst2).to.be.instanceof(TestBooter2);
expect(booterInst2.configureCalled).to.be.True();
const ctx = await bootstrapper.boot({booters: [AnotherBooter]});
const anotherBooterInst = await ctx.get<AnotherBooter>(anotherBooterKey);
expect(anotherBooterInst).to.be.instanceof(AnotherBooter);
expect(anotherBooterInst.phasesCalled).to.eql(['AnotherBooter:configure']);
});

it('no booters run when BootOptions.filter.booters is []', async () => {
const ctx = await bootstrapper.boot({filter: {booters: []}});
const booterInst = await ctx.get(booterKey);
expect(booterInst.configureCalled).to.be.False();
expect(booterInst.loadCalled).to.be.False();
const booterInst = await ctx.get<TestBooter>(booterKey);
expect(booterInst.phasesCalled).to.eql([]);
});

it('only runs booters passed in via BootOptions.filter.booters', async () => {
const ctx = await bootstrapper.boot({
booters: [TestBooter2],
filter: {booters: ['TestBooter2']},
booters: [AnotherBooter],
filter: {booters: ['AnotherBooter']},
});
const booterInst = await ctx.get(booterKey);
const booterInst2 = await ctx.get(booterKey2);
expect(booterInst.configureCalled).to.be.False();
expect(booterInst.loadCalled).to.be.False();
expect(booterInst2.configureCalled).to.be.True();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These assertions are rather unhelpful when they fail:

  1) boot-strapper unit tests
       only runs booters passed in via BootOptions.filter.booters:
     AssertionError: expected false to be true
      at Assertion.fail (packages/testlab/node_modules/should/as-function.js:275:17)
      at Assertion.value (packages/testlab/node_modules/should/as-function.js:356:19)
      at Context.it (packages/boot/test/unit/bootstrapper.unit.ts:4:65)
      at <anonymous>

While I was fixing the cause of the test failure, I rewrote all tests to be more helpful when failing:

     AssertionError: expected Array [ ] to equal Array [ 'TestBooter:configure' ]
      + expected - actual

       [
      +  "TestBooter:configure"
       ]

const testBooterInst = await ctx.get<TestBooter>(booterKey);
const anotherBooterInst = await ctx.get<AnotherBooter>(anotherBooterKey);
const phasesCalled = testBooterInst.phasesCalled.concat(
anotherBooterInst.phasesCalled,
);
expect(phasesCalled).to.eql(['AnotherBooter:configure']);
});

it('only runs phases passed in via BootOptions.filter.phases', async () => {
const ctx = await bootstrapper.boot({filter: {phases: ['configure']}});
const booterInst = await ctx.get(booterKey);
expect(booterInst.configureCalled).to.be.True();
expect(booterInst.loadCalled).to.be.False();
const booterInst = await ctx.get<TestBooter>(booterKey);
expect(booterInst.phasesCalled).to.eql(['TestBooter:configure']);
});

/**
Expand All @@ -80,24 +81,37 @@ describe('boot-strapper unit tests', () => {
* A TestBooter for testing purposes. Implements configure and load.
*/
class TestBooter implements Booter {
configureCalled = false;
loadCalled = false;
private configureCalled = false;
private loadCalled = false;
async configure() {
this.configureCalled = true;
}

async load() {
this.loadCalled = true;
}

get phasesCalled() {
const result = [];
if (this.configureCalled) result.push('TestBooter:configure');
if (this.loadCalled) result.push('TestBooter:load');
return result;
}
}

/**
* A TestBooter for testing purposes. Implements configure.
*/
class TestBooter2 implements Booter {
configureCalled = false;
class AnotherBooter implements Booter {
private configureCalled = false;
async configure() {
this.configureCalled = true;
}

get phasesCalled() {
const result = [];
if (this.configureCalled) result.push('AnotherBooter:configure');
return result;
}
}
});
5 changes: 4 additions & 1 deletion packages/build/config/tslint.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
// These rules catch common errors in JS programming or otherwise
// confusing constructs that are prone to producing bugs.

"await-promise": true,
// User-land promises like Bluebird implement "PromiseLike" (not "Promise")
// interface only. The string "PromiseLike" bellow is needed to
// tell tslint that it's ok to `await` such promises.
"await-promise": [true, "PromiseLike"],
"no-floating-promises": true,
"no-unused-variable": true,
"no-void-expression": [true, "ignore-arrow-function-shorthand"]
Expand Down
8 changes: 4 additions & 4 deletions packages/context/src/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {ResolutionSession} from './resolution-session';
import {instantiateClass} from './resolver';
import {
Constructor,
isPromise,
isPromiseLike,
BoundValue,
ValueOrPromise,
} from './value-promise';
Expand Down Expand Up @@ -176,7 +176,7 @@ export class Binding {
): ValueOrPromise<BoundValue> {
// Initialize the cache as a weakmap keyed by context
if (!this._cache) this._cache = new WeakMap<Context, BoundValue>();
if (isPromise(result)) {
if (isPromiseLike(result)) {
if (this.scope === BindingScope.SINGLETON) {
// Cache the value at owning context level
result = result.then(val => {
Expand Down Expand Up @@ -294,7 +294,7 @@ export class Binding {
* ```
*/
to(value: BoundValue): this {
if (isPromise(value)) {
if (isPromiseLike(value)) {
// Promises are a construct primarily intended for flow control:
// In an algorithm with steps 1 and 2, we want to wait for the outcome
// of step 1 before starting step 2.
Expand Down Expand Up @@ -380,7 +380,7 @@ export class Binding {
ctx!,
session,
);
if (isPromise(providerOrPromise)) {
if (isPromiseLike(providerOrPromise)) {
return providerOrPromise.then(p => p.value());
} else {
return providerOrPromise.value();
Expand Down
Loading