Skip to content

Commit

Permalink
feat(fetch): enhance fetchContext with dispatchOptions and only cache…
Browse files Browse the repository at this point in the history
…_only request in first time

Co-authored-by: S. Amir Mohammad Najafi <[email protected]>
  • Loading branch information
alimd and njfamirm committed Feb 11, 2023
1 parent 5d205b2 commit 1f6b575
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions core/fetch/src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {createLogger, globalAlwatr, isBrowser} from '@alwatr/logger';
import {contextProvider} from '@alwatr/signal';
import {contextProvider, type DispatchOptions} from '@alwatr/signal';
import {getClientId} from '@alwatr/util';

import type {FetchOptions, CacheDuplicate, CacheStrategy} from './type.js';
Expand Down Expand Up @@ -31,12 +31,16 @@ const cacheSupported = 'caches' in globalThis;

const duplicateRequestStorage: Record<string, Promise<Response>> = {};

export async function fetchContext(contextName: string, fetchOption: FetchOptions): Promise<void> {
if (cacheSupported) {
export async function fetchContext(
contextName: string,
fetchOption: FetchOptions,
dispatchOptions?: Partial<DispatchOptions>,
): Promise<void> {
if (cacheSupported && contextProvider.getValue(contextName) == null) {
try {
fetchOption.cacheStrategy = 'cache_only';
const response = await serviceRequest(fetchOption);
contextProvider.setValue<typeof response>(contextName, response);
contextProvider.setValue<typeof response>(contextName, response, dispatchOptions);
}
catch (err) {
if ((err as Error).message === 'fetch_cache_not_found') {
Expand All @@ -56,7 +60,7 @@ export async function fetchContext(contextName: string, fetchOption: FetchOption
response.meta?.lastUpdated === undefined || // skip lastUpdated check
response.meta?.lastUpdated !== contextProvider.getValue<typeof response>(contextName)?.meta?.reversion
) {
contextProvider.setValue<typeof response>(contextName, response);
contextProvider.setValue<typeof response>(contextName, response, dispatchOptions);
}
}
catch (err) {
Expand Down

0 comments on commit 1f6b575

Please sign in to comment.