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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ 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.
- `Context.merge(context)`: Merge new context input to create a new async context object.
- `Context.clear()`: Clear the context as if the context is created with no context argument during creation or with `set()` method calls. Used mostly for testing.

[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
11 changes: 11 additions & 0 deletions src/createContext.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,14 @@ test('get() rejects if context does not exist', async () => {
name: 'ContextNotSet'
})
})

test('clear() reverts context to unset state. This is used for testing', async () => {
const ctx = createContext({})

ctx.clear()

const err = a.throws(() => ctx.get(), IsoError)
a.satisfies(err, {
name: 'ContextNotSet'
})
})
4 changes: 4 additions & 0 deletions src/createContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ContextNotSet } from './errors'
export type Context<T> = {
get(): Promise<T>,
set(context: T | (() => Promise<T>)): void
clear(): void
merge<R>(context: R | (() => Promise<R>)): Context<T & R>
}

Expand All @@ -20,6 +21,9 @@ export function createContext<T extends Record<string | symbol, any>>(context?:
set(context: (() => Promise<T>) | T) {
ready = typeof context === 'function' ? (context as any)() : Promise.resolve(context)
},
clear() {
ready = undefined
},
merge(context) {
return createContext(async () => {
const r = typeof context === 'function' ? await (context as any)() : context
Expand Down