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

fix(core): scoped factories should not fail with optional deps #9922

Merged
merged 3 commits into from
Jul 12, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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