From 1c3191ad95f09a49e5037750305a14be25953b7f Mon Sep 17 00:00:00 2001 From: uri Date: Sat, 6 Apr 2024 18:00:06 +0300 Subject: [PATCH] factor out context --- src/context.test.ts | 36 ------------------------------------ src/context.ts | 21 --------------------- 2 files changed, 57 deletions(-) delete mode 100644 src/context.test.ts delete mode 100644 src/context.ts diff --git a/src/context.test.ts b/src/context.test.ts deleted file mode 100644 index 2e06aba..0000000 --- a/src/context.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { assertEquals } from "std-assert"; -import { context } from "./context.ts"; - -Deno.test("inject and access", async () => { - const { inject, access } = context((): string => "nothing injected"); - const withString = inject(() => "injected"); - const f = () => Promise.resolve(access()); - assertEquals(await withString(f)(), "injected"); - assertEquals(await f(), "nothing injected"); -}); - -Deno.test("override", async () => { - const { inject, access } = context((): string => "nothing injected"); - const withStringX = inject(() => "X"); - const withStringY = inject(() => "Y"); - const f = () => Promise.resolve(access()); - assertEquals(await withStringX(f)(), "X"); - assertEquals(await withStringY(withStringX(f))(), "X"); - assertEquals(await withStringX(withStringY(f))(), "Y"); - assertEquals(await f(), "nothing injected"); -}); - -Deno.test("use context within context", async () => { - const { inject: injectA, access: accessA } = context((): string => - "nothing injected A" - ); - const { inject: injectB, access: accessB } = context((): string => - "nothing injected B" - ); - const withA = injectA(() => "A"); - const withAB = injectB(() => accessA() + "B"); - const f = () => Promise.resolve(accessB()); - assertEquals(await withA(f)(), "nothing injected B"); - assertEquals(await withA(withAB(f))(), "AB"); - assertEquals(await f(), "nothing injected B"); -}); diff --git a/src/context.ts b/src/context.ts deleted file mode 100644 index 9b73e9d..0000000 --- a/src/context.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { AsyncLocalStorage } from "node:async_hooks"; -import { letIn } from "./operator.ts"; -import { Func } from "./typing.ts"; - -const withContext = (storage: AsyncLocalStorage, context: T) => -(f: F): F => -// @ts-expect-error cannot infer -(...xs) => - new Promise((resolve, reject) => - storage.run(context, () => { - f(...xs).then(resolve).catch(reject); - }) - ); - -export const context = (fallbackFn: F) => - letIn(new AsyncLocalStorage(), (storage) => ({ - inject: (fn: F) => withContext(storage, fn), - // Cannot be made point free because has to call `storage.getStore` contextually. - access: ((...xs: Parameters) => - (storage.getStore() ?? fallbackFn)(...xs)) as F, - }));