Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ async function someOtherFunc(

- `createContext(context)`: Create a new async context object. The input can be an object (sync) or a `Promise` returning function (async).
- `Context.merge(context)`: Merge new context input to create a new async context object.
- `Context.set(context)`: Set context to a new value. This is used when `createContext()` is made by the producer while `set()` is called by consumer.

[circleci-image]: https://circleci.com/gh/unional/async-fp/tree/master.svg?style=shield
[circleci-url]: https://circleci.com/gh/unional/async-fp/tree/master
Expand Down
16 changes: 16 additions & 0 deletions src/createContext.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,19 @@ test('sync context merge', async () => {

expect(await actual.get()).toEqual({ a: 1, b: 'b' })
})

test('async context set', async () => {
const ctx = createContext<{ a: number }>()

ctx.set(async () => ({ a: 1 }))

expect(await ctx.get()).toEqual({ a: 1 })
})

test('sync context set', async () => {
const ctx = createContext<{ a: number }>()

ctx.set({ a: 1 })

expect(await ctx.get()).toEqual({ a: 1 })
})
8 changes: 6 additions & 2 deletions src/createContext.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
export type Context<T> = {
get(): Promise<T>,
set(context: T | (() => Promise<T>)): void
merge<R>(context: R | (() => Promise<R>)): Context<T & R>
}

export function createContext<T extends Record<string | symbol, any>>(context: (() => Promise<T>) | T): Context<T> {
const ready = typeof context === 'function' ? (context as any)() : Promise.resolve(context)
export function createContext<T extends Record<string | symbol, any>>(context?: (() => Promise<T>) | T): Context<T> {
let ready = typeof context === 'function' ? (context as any)() : Promise.resolve(context)
return {
get() {
return ready
},
set(context: (() => Promise<T>) | T) {
ready = typeof context === 'function' ? (context as any)() : Promise.resolve(context)
},
merge(context) {
return createContext(async () => {
const r = typeof context === 'function' ? await (context as any)() : context
Expand Down