Skip to content

Commit

Permalink
diScope
Browse files Browse the repository at this point in the history
  • Loading branch information
darky committed May 23, 2023
1 parent e8e0a3a commit 43125f5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
15 changes: 15 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,21 @@ export const diExists = () => (als.getStore() == null) === false

export const diContext = (): AlsContext => ({ deps: new Map(), once: new Map(), state: new Map() })

export const diScope = <T extends { [key: string]: any }>(scope: T, init?: () => void): T => {
const ctx = diContext()
if (init) {
diInit(init, ctx)
}
return Object.fromEntries(
Object.entries(scope).map(([key, fn]) => [
key,
function (this: unknown, ...args: unknown[]) {
return diInit(() => fn.apply(this, args), ctx)
},
])
) as T
}

const storeOrError = () => {
const store = als.getStore()

Expand Down
20 changes: 20 additions & 0 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
clearGlobalState,
diHas,
diContext,
diScope,
} from './index.js'
import EventEmitter from 'events'

Expand Down Expand Up @@ -344,3 +345,22 @@ test('diContext', () => {
state: new Map(),
})
})

test('diScope', () => {
const inc = dis((resp: number, n: number) => resp + n, 0)
const checkScope = di((scope: string) => diDep<boolean>(scope))

const scope1 = diScope({ inc, checkScope }, () => diSet('scope1', true))
const scope2 = diScope({ inc, checkScope }, () => diSet('scope2', true))

assert.strictEqual(scope1.checkScope('scope1'), true)
assert.rejects(async () => scope1.checkScope('scope2'), new Error('Dependency with key scope2 not registered!'))
assert.strictEqual(scope2.checkScope('scope2'), true)
assert.rejects(async () => scope2.checkScope('scope1'), new Error('Dependency with key scope1 not registered!'))

scope1.inc(2)
scope2.inc(5)

assert.strictEqual(scope1.inc(), 2)
assert.strictEqual(scope2.inc(), 5)
})

0 comments on commit 43125f5

Please sign in to comment.