Skip to content

Commit

Permalink
feat: actions bound to a runtime now return a Promise<void> represent…
Browse files Browse the repository at this point in the history
…ing their completion (#717)

BREAKING CHANGE: This is a type-only change
  • Loading branch information
tdreyno authored Mar 14, 2023
1 parent c4f3d91 commit e1a80f5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 9 deletions.
12 changes: 7 additions & 5 deletions src/__tests__/boundActions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,17 @@ describe("Bound actions", () => {

const runtime = createRuntime(context, ["Add", "Multiply"])

const boundActions = runtime.bindActions({ add, multiply })

const onChange = jest.fn()
runtime.onContextChange(onChange)

await Promise.all([
runtime.run(add(2)),
runtime.run(multiply(2)),
runtime.run(add(3)),
runtime.run(multiply(5)),
runtime.run(add(1)),
boundActions.add(2).asPromise(),
boundActions.multiply(2).asPromise(),
boundActions.add(3).asPromise(),
boundActions.multiply(5).asPromise(),
boundActions.add(1).asPromise(),
])

expect(runtime.currentState().data).toBe(36)
Expand Down
15 changes: 12 additions & 3 deletions src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,24 @@ export class Runtime {

bindActions<
AM extends { [key: string]: (...args: Array<any>) => Action<any, any> },
>(actions: AM): AM {
PM = {
[K in keyof AM]: (...args: Parameters<AM[K]>) => {
asPromise: () => Promise<void>
}
},
>(actions: AM): PM {
return Object.keys(actions).reduce((sum, key) => {
sum[key] = (...args: Array<any>) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-non-null-assertion
return this.run(actions[key]!(...args))
const promise = this.run(actions[key]!(...args))

return {
asPromise: () => promise,
}
}

return sum
}, {} as Record<string, any>) as AM
}, {} as Record<string, any>) as PM
}

async run(action: Action<any, any>): Promise<void> {
Expand Down
7 changes: 6 additions & 1 deletion src/svelte/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@ import { Runtime, createRuntime } from "../runtime.js"
export interface ContextValue<
SM extends { [key: string]: BoundStateFn<any, any, any> },
AM extends { [key: string]: (...args: Array<any>) => Action<any, any> },
PM = {
[K in keyof AM]: (...args: Parameters<AM[K]>) => {
asPromise: () => Promise<void>
}
},
> {
currentState: ReturnType<SM[keyof SM]>
context: Context
actions: AM
actions: PM
runtime?: Runtime
}

Expand Down

0 comments on commit e1a80f5

Please sign in to comment.