Skip to content

Commit

Permalink
feat(fetch): fetch json
Browse files Browse the repository at this point in the history
Co-authored-by: Ali Mihandoost <[email protected]>
  • Loading branch information
njfamirm and alimd committed Jan 21, 2024
1 parent 8b88c81 commit b089f12
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 5 deletions.
54 changes: 53 additions & 1 deletion packages/fetch/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,62 @@
import {handleCacheStrategy_, logger_, processOptions_, cacheSupported} from './core';

import type {FetchOptions} from './type';
import type {FetchOptions, ResponseError, ResponseSuccess} from './type';
import type {Json, JsonObject} from '@alwatr/type-helper';

Check failure on line 4 in packages/fetch/src/main.ts

View workflow job for this annotation

GitHub Actions / Build & Lint Typescript

'Json' is defined but never used

export {cacheSupported};
export type * from './type';

/**
* It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,
* remove duplicates, etc.
*
* @see {@link FetchOptions}
* @see {@link ResponseSuccess}
* @see {@link ResponseError}
*
* @param options Fetch options.
*
* @returns A success or error response.
*
* @example
* ```typescript
* const responseJson = await fetchJson({
* url: '/api/products',
* queryParameters: {limit: 10},
* timeout: 8_000,
* retry: 3,
* cacheStrategy: 'stale_while_revalidate',
* cacheDuplicate: 'auto',
* });
* ```
*/
export async function fetchJson<T extends JsonObject>(options: FetchOptions): Promise<ResponseSuccess<T> | ResponseError> {
let response;
let responseText;
let responseJson;
try {
response = await fetch(options);
responseText = await response.text();
responseJson = JSON.parse(responseText) as ResponseSuccess<T>;
responseJson.ok = true;
responseJson.statusCode = response.status;
return responseJson;
}
catch (error) {
const responseError: ResponseError = {
ok: false,
statusCode: response?.status,
statusText: response?.statusText,
errorCode: (responseJson?.errorCode as string) ?? (error as Error).message,
responseText,
meta: responseJson?.meta as JsonObject,
};

logger_.accident('fetchJson', 'fetch_failed', {responseError, error});
return responseError;
}
}

/**
* It's a wrapper around the browser's `fetch` function that adds retry pattern, timeout, cacheStrategy,
* remove duplicates, etc.
Expand Down
22 changes: 18 additions & 4 deletions packages/fetch/src/type.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {Dictionary, Json} from '@alwatr/type-helper';
import type {Dictionary, Json, JsonObject} from '@alwatr/type-helper';

/**
* Represents the available HTTP methods.
Expand Down Expand Up @@ -132,7 +132,21 @@ export interface FetchOptions extends RequestInit {
* Alwatr token scheme
*/
alwatrAuth?: {
userId: string,
userToken: string,
}
userId: string;
userToken: string;
};
}

export type ResponseSuccess<T extends JsonObject> = T & {
ok: true;
statusCode: number;
};

export type ResponseError = {
ok: false;
statusCode?: number;
statusText?: string;
errorCode: string;
responseText?: string;
meta?: JsonObject;
}

0 comments on commit b089f12

Please sign in to comment.