From 55d38a1a858f362a8bc3738c277b15dff4c4c09c Mon Sep 17 00:00:00 2001 From: "Homa Wong (unional)" Date: Wed, 10 Apr 2019 23:41:07 -0700 Subject: [PATCH] feat: add set() --- README.md | 1 + src/createContext.spec.ts | 16 ++++++++++++++++ src/createContext.ts | 8 ++++++-- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4b4d723..6e4eec6 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/createContext.spec.ts b/src/createContext.spec.ts index eaf0b66..90f214c 100644 --- a/src/createContext.spec.ts +++ b/src/createContext.spec.ts @@ -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 }) +}) diff --git a/src/createContext.ts b/src/createContext.ts index ac64db6..481d5f8 100644 --- a/src/createContext.ts +++ b/src/createContext.ts @@ -1,14 +1,18 @@ export type Context = { get(): Promise, + set(context: T | (() => Promise)): void merge(context: R | (() => Promise)): Context } -export function createContext>(context: (() => Promise) | T): Context { - const ready = typeof context === 'function' ? (context as any)() : Promise.resolve(context) +export function createContext>(context?: (() => Promise) | T): Context { + let ready = typeof context === 'function' ? (context as any)() : Promise.resolve(context) return { get() { return ready }, + set(context: (() => Promise) | 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