Skip to content

Commit 7762117

Browse files
author
Julien Heller
committed
Added check for Service option
1 parent e7cbb28 commit 7762117

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/ContainerInstance.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {ObjectType} from "./types/ObjectType";
66
import {ServiceIdentifier} from "./types/ServiceIdentifier";
77
import {ServiceMetadata} from "./types/ServiceMetadata";
88
import {AsyncInitializedService} from "./types/AsyncInitializedService";
9+
import { MissingInitializedPromiseError } from "./error/MissingInitializedPromiseError";
910

1011
/**
1112
* TypeDI can have multiple containers.
@@ -499,10 +500,13 @@ export class ContainerInstance {
499500
if (type)
500501
this.applyPropertyHandlers(type, value);
501502

502-
if (value instanceof AsyncInitializedService) {
503-
return new Promise((resolve) => {
504-
value._initialized.then(() => resolve(value));
505-
});
503+
if (value instanceof AsyncInitializedService || service.asyncInitialization) {
504+
return new Promise((resolve) => {
505+
if (!(value._initialized instanceof Promise) && service.asyncInitialization) {
506+
throw new MissingInitializedPromiseError(service.value);
507+
}
508+
value._initialized.then(() => resolve(value));
509+
});
506510
}
507511
return Promise.resolve(value);
508512
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* Thrown when DI cannot inject value into property decorated by @Inject decorator.
3+
*/
4+
export class MissingInitializedPromiseError extends Error {
5+
name = "MissingInitializedPromiseError";
6+
7+
constructor(value: any) {
8+
super(
9+
(value._initialized
10+
? `asyncInitialization: true was used, but ${value.name}#_initialized is not a Promise. `
11+
: `asyncInitialization: true was used, but ${value.name}#_initialized is undefined. `) +
12+
`You will need to either extend the abstract AsyncInitializedService class, or assign ` +
13+
`${value.name}#_initialized to a Promise in your class' constructor that resolves when all required ` +
14+
`initialization is complete.`
15+
);
16+
Object.setPrototypeOf(this, MissingInitializedPromiseError.prototype);
17+
}
18+
19+
}

0 commit comments

Comments
 (0)