Skip to content

Commit

Permalink
feat(fetch): fetchContext (#803)
Browse files Browse the repository at this point in the history
  • Loading branch information
AliMD authored Feb 11, 2023
2 parents 5e40185 + d63d17e commit e4dbe33
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
3 changes: 2 additions & 1 deletion core/fetch/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
39 changes: 37 additions & 2 deletions core/fetch/src/fetch.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -30,12 +31,46 @@ const cacheSupported = 'caches' in globalThis;

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

export async function fetchContext(contextName: string, fetchOption: FetchOptions): Promise<void> {
if (cacheSupported) {
try {
fetchOption.cacheStrategy = 'cache_only';
const response = await serviceRequest(fetchOption);
contextProvider.setValue<typeof response>(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<typeof response>(contextName)?.meta?.reversion
) {
contextProvider.setValue<typeof response>(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<AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>> {
Expand Down
3 changes: 2 additions & 1 deletion core/fetch/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"exclude": [],
"references": [
{"path": "../logger"},
{"path": "../math"},
{"path": "../util"},
{"path": "../signal"},
{"path": "../type"}
]
}

0 comments on commit e4dbe33

Please sign in to comment.