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

[DX] Replace axios with fetch #376

Open
AleksandarDev opened this issue Nov 21, 2022 · 2 comments
Open

[DX] Replace axios with fetch #376

AleksandarDev opened this issue Nov 21, 2022 · 2 comments
Labels
enhancement New feature or request good first issue Good for newcomers question Further information is requested

Comments

@AleksandarDev
Copy link
Member

We have abstraction layer with HttpService methods so we can replace existing implementation that is using Axios with fetch which will reduce bundle size and dependencies/number of update PRs.

@AleksandarDev AleksandarDev added enhancement New feature or request good first issue Good for newcomers question Further information is requested labels Nov 21, 2022
@radovix
Copy link
Member

radovix commented Nov 23, 2022

Axios allows us to easily write all kind of interceptors (e.g. interceptor for checking whether request failed with 401 status code or interceptor for doing the token refreshing). How easy is to handle those cases without with just fetch?

@AleksandarDev
Copy link
Member Author

AleksandarDev commented Nov 23, 2022

@radovix As we have HttpService with a request function. That can easily be handled there by reading response.status and doing required logic. We don't encourage using axios in app directly anyway so adding interceptors globally is not that useful in our case.

Example:

  async function requestAsync(
    url: string,
    method: 'get' | 'post' | 'put' | 'delete',
    data?: any,
    headers?: Record<string, string>,
    skipAuth?: boolean
  ) {
    const token = skipAuth ? '' : await _getBearerTokenAsync()
    try {
        // Construct query URL (with params if we are doing GET)
        // We always featch with absolute URL, if provided with relative resolve to API url
        var urlResolved = new URL(isAbsoluteUrl(url) ? url : getApiUrl(url));
        if (method === 'get' && data) {
            urlResolved.search = new URLSearchParams(data).toString();
        }

        const response = await fetch(urlResolved, {
            method: method,
            body: method !== 'get' ? JSON.stringify(data) : undefined,
            headers: {
                Accept: 'application/json',
                Authorization: token,
                'Content-Type': 'application/json',
                ...headers
            },
        });
        
        // Return JSON - we expect response to always be JSON or empty
        if (response.status === 200) {
            try {
                return await response.json();
            } catch {
                return null;
            }
        }

        if (response.status === 403) {
            // TODO: Redirect to login
        }

        // Don't know how to handle other status codes
        let bodyText: string | null = null;
        try {
            bodyText = await response.text()
        } catch {
            bodyText = 'empty response';
        }
        throw new Error(`Got status ${response.statusText} (${response.status}): bodyText`);
    } catch(err) {
        console.error('Unknown API error', err);
        throw err;
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants