Skip to content

Commit

Permalink
Throw better error on incorrect asyncInit (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
kibertoad authored Dec 20, 2024
1 parent 46350b5 commit 4f7576f
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 5 deletions.
11 changes: 10 additions & 1 deletion lib/awilixManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,18 @@ export async function asyncInit(diContainer: AwilixContainer) {
for (const [key, description] of dependenciesWithAsyncInit) {
const resolvedValue = diContainer.resolve(key)
if (description.asyncInit === true) {
if (!('asyncInit' in resolvedValue)) {
throw new Error(`Method asyncInit does not exist on dependency ${key}`)
}
await resolvedValue.asyncInit(diContainer.cradle)
} else {
// @ts-ignore
// @ts-expect-error
if (!(description.asyncInit in resolvedValue)) {
throw new Error(
`Method ${description.asyncInit} for asyncInit does not exist on dependency ${key}`,
)
}
// @ts-expect-error
await resolvedValue[description.asyncInit](diContainer.cradle)
}
}
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
"awilix": ">=9.0.0"
},
"devDependencies": {
"@biomejs/biome": "^1.8.2",
"@kibertoad/biome-config": "^1.2.0",
"@types/node": "^20.14.8",
"@biomejs/biome": "^1.9.4",
"@kibertoad/biome-config": "^1.2.1",
"@types/node": "^20.17.10",
"@vitest/coverage-v8": "^1.6.0",
"del-cli": "^6.0.0",
"typescript": "^5.5.2",
"typescript": "^5.7.2",
"vitest": "^1.6.0"
},
"engines": {
Expand Down
34 changes: 34 additions & 0 deletions test/awilixManager.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,40 @@ describe('awilixManager', () => {
expect(dependency3.isInitted).toBe(true)
})

it('throws a clear error when asyncInit method does not exist', async () => {
const diContainer = createContainer({
injectionMode: 'PROXY',
})
diContainer.register(
'dependency1',
asClass(AsyncInitClass, {
lifetime: 'SINGLETON',
asyncInit: 'dummy',
}),
)

await expect(() => asyncInit(diContainer)).rejects.toThrowError(
'Method dummy for asyncInit does not exist on dependency dependency1',
)
})

it('throws a clear error when default asyncInit method does not exist', async () => {
const diContainer = createContainer({
injectionMode: 'PROXY',
})
diContainer.register(
'dependency1',
asClass(AsyncDisposeClass, {
lifetime: 'SINGLETON',
asyncInit: true,
}),
)

await expect(() => asyncInit(diContainer)).rejects.toThrowError(
'Method asyncInit does not exist on dependency dependency1',
)
})

it('execute asyncInit on registered dependencies and use dependencies from cradle', async () => {
const diContainer = createContainer({
injectionMode: 'PROXY',
Expand Down

0 comments on commit 4f7576f

Please sign in to comment.