From d63d17ecb58221159dc45a473fdd1c992d306d2b Mon Sep 17 00:00:00 2001 From: Ali Mihandoost Date: Sat, 11 Feb 2023 13:30:21 +0330 Subject: [PATCH] feat(fetch): fetchContext --- core/fetch/package.json | 3 ++- core/fetch/src/fetch.ts | 39 +++++++++++++++++++++++++++++++++++++-- core/fetch/tsconfig.json | 3 ++- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/core/fetch/package.json b/core/fetch/package.json index cae4d323d..677cbbc59 100644 --- a/core/fetch/package.json +++ b/core/fetch/package.json @@ -35,7 +35,8 @@ }, "dependencies": { "@alwatr/logger": "^0.29.0", - "@alwatr/math": "^0.29.0", + "@alwatr/util": "^0.29.0", + "@alwatr/signal": "^0.29.0", "tslib": "^2.5.0" }, "devDependencies": { diff --git a/core/fetch/src/fetch.ts b/core/fetch/src/fetch.ts index 75039a1bc..711644dfa 100644 --- a/core/fetch/src/fetch.ts +++ b/core/fetch/src/fetch.ts @@ -1,5 +1,6 @@ import {createLogger, globalAlwatr, isBrowser} from '@alwatr/logger'; -import {getClientId} from '@alwatr/math'; +import {contextProvider} from '@alwatr/signal'; +import {getClientId} from '@alwatr/util'; import type {FetchOptions, CacheDuplicate, CacheStrategy} from './type.js'; import type { @@ -30,12 +31,46 @@ const cacheSupported = 'caches' in globalThis; const duplicateRequestStorage: Record> = {}; +export async function fetchContext(contextName: string, fetchOption: FetchOptions): Promise { + if (cacheSupported) { + try { + fetchOption.cacheStrategy = 'cache_only'; + const response = await serviceRequest(fetchOption); + contextProvider.setValue(contextName, response); + } + catch (err) { + if ((err as Error).message === 'fetch_cache_not_found') { + logger.logOther('fetchContext:', 'fetch_cache_not_found'); + } + else { + logger.error('fetchContext', 'fetch_failed', err); + throw err; + } + } + } + + try { + fetchOption.cacheStrategy = 'update_cache'; + const response = await serviceRequest(fetchOption); + if ( + response.meta?.lastUpdated === undefined || // skip lastUpdated check + response.meta?.lastUpdated !== contextProvider.getValue(contextName)?.meta?.reversion + ) { + contextProvider.setValue(contextName, response); + } + } + catch (err) { + logger.error('fetchContext', 'fetch_failed', err); + throw err; + } +} + /** * Fetch from alwatr services and return standard response. */ export async function serviceRequest< TData extends StringifyableRecord = StringifyableRecord, - TMeta extends StringifyableRecord = StringifyableRecord, + TMeta extends StringifyableRecord = StringifyableRecord >( options: FetchOptions, ): Promise | AlwatrServiceResponseSuccessWithMeta> { diff --git a/core/fetch/tsconfig.json b/core/fetch/tsconfig.json index f136d7ebf..1f6b770ce 100644 --- a/core/fetch/tsconfig.json +++ b/core/fetch/tsconfig.json @@ -11,7 +11,8 @@ "exclude": [], "references": [ {"path": "../logger"}, - {"path": "../math"}, + {"path": "../util"}, + {"path": "../signal"}, {"path": "../type"} ] }