From 5877b32dec7e4f4b61bf8a24e833c89bd808c8d2 Mon Sep 17 00:00:00 2001 From: Roberto Bianchi Date: Tue, 23 Apr 2024 19:00:45 +0200 Subject: [PATCH] feat(store): Throw if store not initialized (#3) * feat(store): Throw if store not initialized Signed-off-by: Roberto Bianchi * Update * Add test --------- Signed-off-by: Roberto Bianchi --- asyncforge.js | 5 ++++- test/do-not-start-memo.test.js | 13 +++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/asyncforge.js b/asyncforge.js index 2ac45a4..b3d3f87 100644 --- a/asyncforge.js +++ b/asyncforge.js @@ -36,7 +36,10 @@ function memo (name) { function get () { const store = asyncLocalStorage.getStore() - return store?.[sym] + if (!store) { + throw new Error(`asyncforge store is not initialized for ${name}`) + } + return store[sym] } function set (value) { diff --git a/test/do-not-start-memo.test.js b/test/do-not-start-memo.test.js index 13e6c52..267e517 100644 --- a/test/do-not-start-memo.test.js +++ b/test/do-not-start-memo.test.js @@ -8,7 +8,7 @@ test('memo without start', async (t) => { const p = tspl(t, { plan: 6 }) const a = memo() - p.deepStrictEqual(a(), undefined) + p.throws(() => a(), { message: 'asyncforge store is not initialized for memo0' }) a.set({ value: 'bar' }) p.deepStrictEqual(a(), { value: 'bar' }) @@ -38,11 +38,20 @@ test('memo without start', async (t) => { await p.completed }) +test('memo with name', async (t) => { + const p = tspl(t, { plan: 1 }) + const a = memo('custom-name') + + p.throws(() => a(), { message: 'asyncforge store is not initialized for custom-name' }) + + await p.completed +}) + test('nested', async (t) => { const p = tspl(t, { plan: 5 }) const a = memo() - p.deepStrictEqual(a(), undefined) + p.throws(() => a(), { message: 'asyncforge store is not initialized for memo1' }) a.set({ value: 'bar' }) p.deepStrictEqual(a(), { value: 'bar' })