Skip to content

Commit

Permalink
Merge pull request #9922 from nestjs/fix/scoped-factories-optional-deps
Browse files Browse the repository at this point in the history
fix(core): scoped factories should not fail with optional deps
  • Loading branch information
kamilmysliwiec committed Jul 12, 2022
2 parents 976cdf3 + ced2acf commit 76923e7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
37 changes: 37 additions & 0 deletions integration/injector/e2e/optional-factory-provider-dep.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Scope } from '@nestjs/common';
import { UnknownDependenciesException } from '@nestjs/core/errors/exceptions/unknown-dependencies.exception';
import { Test } from '@nestjs/testing';
import { expect } from 'chai';
Expand Down Expand Up @@ -38,6 +39,42 @@ describe('Optional factory provider deps', () => {
const factoryProvider = moduleRef.get('FACTORY');
expect(factoryProvider).to.equal(defaultValue);
});
it('"undefined" should be injected into the factory function (scoped provider)', async () => {
const MY_PROVIDER = 'MY_PROVIDER';
const FIRST_OPTIONAL_DEPENDENCY = 'FIRST_OPTIONAL_DEPENDENCY';
const SECOND_OPTIONAL_DEPENDENCY = 'SECOND_OPTIONAL_DEPENDENCY';

const module = await Test.createTestingModule({
providers: [
{
provide: FIRST_OPTIONAL_DEPENDENCY,
useValue: 'first',
},
{
provide: MY_PROVIDER,
scope: Scope.REQUEST,
inject: [
{
token: FIRST_OPTIONAL_DEPENDENCY,
optional: true,
},
{
token: SECOND_OPTIONAL_DEPENDENCY,
optional: true,
},
],
useFactory: (first?: string, second?: string) => {
return { first, second };
},
},
],
}).compile();

expect(await module.resolve(MY_PROVIDER)).to.deep.equal({
first: 'first',
second: undefined,
});
});
});
});
describe('otherwise', () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/injector/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,7 @@ export class Injector {
inquirer?: InstanceWrapper,
parentInquirer?: InstanceWrapper,
): Promise<any[]> {
const hosts = await Promise.all(
const hosts: Array<InstanceWrapper<any> | undefined> = await Promise.all(
metadata.map(async item =>
this.resolveScopedComponentHost(
item,
Expand All @@ -791,7 +791,7 @@ export class Injector {
const inquirerId = this.getInquirerId(inquirer);
return hosts.map(
item =>
item.getInstanceByContextId(
item?.getInstanceByContextId(
this.getContextId(contextId, item),
inquirerId,
).instance,
Expand Down

0 comments on commit 76923e7

Please sign in to comment.