Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(fetch): serviceRequest #513

Merged
merged 3 commits into from
Dec 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 51 additions & 14 deletions core/fetch/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,11 @@ import type {
CacheStrategy,
AlwatrDocumentObject,
AlwatrServiceResponse,
AlwatrServiceResponseSuccessWithMeta,
AlwatrServiceResponseSuccess,
} from './type.js';

export {
FetchOptions,
CacheDuplicate,
CacheStrategy,
AlwatrDocumentObject,
AlwatrServiceResponse,
};
export {FetchOptions, CacheDuplicate, CacheStrategy, AlwatrDocumentObject, AlwatrServiceResponse};

const logger = createLogger('alwatr/fetch');

Expand All @@ -28,6 +24,46 @@ const cacheSupported = 'caches' in globalThis;

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

/**
* Fetch from alwatr services and return standard response.
*/
export async function serviceRequest<TData = Record<string, unknown>, TMeta = Record<string, unknown>>(
options: FetchOptions,
): Promise<AlwatrServiceResponseSuccess<TData> | AlwatrServiceResponseSuccessWithMeta<TData, TMeta>> {
logger.logMethod('serviceRequest');

const response = await fetch(options);

let responseJson: AlwatrServiceResponse<TData, TMeta>;
try {
responseJson = await response.json();
}
catch (err) {
let responseText: string | null = null;
try {
responseText = await response.text();
}
catch {
logger.accident('serviceRequest', 'invalid_response', 'Cannot extract response.text()');
}
logger.error('serviceRequest', 'invalid_json', err, {responseText});
throw new Error('invalid_json');
}

if (responseJson.ok !== true) {
logger.error('serviceRequest', 'fetch_nok', {responseJson});
if (typeof responseJson.errorCode === 'string') {
throw new Error(responseJson.errorCode);
}
// else
throw new Error('fetch_nok');
}

// TODO: generate fetch signals hook (for easier handle loading and show error toast)

return responseJson;
}

/**
* It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,
* remove duplicates, etc.
Expand All @@ -45,10 +81,10 @@ const duplicateRequestStorage: Record<string, Promise<Response>> = {};
* });
* ```
*/
export function fetch(_options: FetchOptions): Promise<Response> {
const options = _processOptions(_options);
logger.logMethodArgs('fetch', {options});
return _handleCacheStrategy(options);
export function fetch(options: FetchOptions): Promise<Response> {
const _options = _processOptions(options);
logger.logMethodArgs('fetch', {options, _options});
return _handleCacheStrategy(_options);
}

/**
Expand Down Expand Up @@ -140,11 +176,12 @@ async function _handleCacheStrategy(options: Required<FetchOptions>): Promise<Re

case 'cache_only': {
const cachedResponse = await cacheStorage.match(request);
if (cachedResponse != null) {
return cachedResponse;
if (cachedResponse == null) {
logger.error('_handleCacheStrategy', 'fetch_cache_not_found', {request});
throw new Error('fetch_cache_not_found');
}
// else
throw new Error('fetch_cache_not_found');
return cachedResponse;
}

case 'network_first': {
Expand Down
12 changes: 12 additions & 0 deletions core/fetch/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,15 @@ export type AlwatrServiceResponse<TData = Record<string, unknown>, TMeta = Recor
| AlwatrServiceResponseSuccess<TData>
| AlwatrServiceResponseSuccessWithMeta<TData, TMeta>
| AlwatrServiceResponseFailed;

export type AlwatrDocumentMeta = {
formatVersion: number;
reversion: number;
lastUpdated: number;
lastAutoId: number;
};

export type AlwatrDocumentStorage<T extends AlwatrDocumentObject> = Omit<
AlwatrServiceResponseSuccessWithMeta<Record<string, T | undefined>, AlwatrDocumentMeta>,
'statusCode' | 'errorCode'
>;