Skip to content

Commit

Permalink
[NO-TASK] add responseType to CallConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
lapatric committed Dec 9, 2024
1 parent af31db0 commit ce79ffe
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
24 changes: 19 additions & 5 deletions packages/react/src/hooks/api.hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@ export interface ApiInterface {
call: <T>(config: CallConfig) => Promise<T>;
}

export enum ResponseType {
JSON = 'json',
TEXT = 'text',
BLOB = 'blob',
}

export interface CallConfig {
url: string;
method: 'GET' | 'PUT' | 'POST' | 'DELETE';
version?: string;
data?: any;
noJson?: boolean;
noJsonResponse?: boolean;
responseType?: ResponseType;
specialHandling?: SpecialHandling;
token?: string;
}
Expand All @@ -28,6 +34,7 @@ export function useApi(): ApiInterface {

const url = process.env.REACT_APP_API_URL ?? 'https://api.dfx.swiss';
const defaultVersion = 'v1';
const defaultResponseType = ResponseType.JSON;

async function call<T>(config: CallConfig): Promise<T> {
return fetchFrom<T>(config).catch((error: ApiError) => {
Expand All @@ -42,6 +49,7 @@ export function useApi(): ApiInterface {
async function fetchFrom<T>(config: CallConfig): Promise<T> {
const version = config.version ?? defaultVersion;
const baseUrl = `${url}/${version}`;
const responseType = config.responseType ?? ResponseType.JSON;

return fetch(
`${baseUrl}/${config.url}`,
Expand All @@ -51,12 +59,18 @@ export function useApi(): ApiInterface {
config.specialHandling?.action?.();
}
if (response.ok) {
if (config.noJsonResponse) {
return response.text() as unknown as T;
} else {
return response.json().catch(() => undefined);
switch (responseType) {
case ResponseType.JSON:
return response.json().catch(() => undefined) as Promise<T>;
case ResponseType.TEXT:
return response.text() as Promise<T>;
case ResponseType.BLOB:
return response.blob() as Promise<T>;
default:
throw new Error('Unknown response type');
}
}

return response.json().then((body) => {
throw body;
});
Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export { useSupportChatContext } from './contexts/support.context';

// Hooks
export { useApiSession } from './hooks/api-session.hook';
export { useApi, CallConfig } from './hooks/api.hook';
export { useApi, CallConfig, ResponseType } from './hooks/api.hook';
export { useAsset } from './hooks/asset.hook';
export { useAuth } from './hooks/auth.hook';
export { useBankAccount, CreateBankAccount, UpdateBankAccount } from './hooks/bank-account.hook';
Expand Down

0 comments on commit ce79ffe

Please sign in to comment.