diff --git a/README.md b/README.md index 5c134ac..94de1dd 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/createContext.spec.ts b/src/createContext.spec.ts index 120178d..a21eafe 100644 --- a/src/createContext.spec.ts +++ b/src/createContext.spec.ts @@ -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' + }) +}) diff --git a/src/createContext.ts b/src/createContext.ts index 6e22885..7a186d3 100644 --- a/src/createContext.ts +++ b/src/createContext.ts @@ -3,6 +3,7 @@ import { ContextNotSet } from './errors' export type Context = { get(): Promise, set(context: T | (() => Promise)): void + clear(): void merge(context: R | (() => Promise)): Context } @@ -20,6 +21,9 @@ export function createContext>(context?: set(context: (() => Promise) | 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