DEV Community

Scott Hu
Scott Hu

Posted on

alova instance of alovajs, a request strategy library

alova is a lightweight request strategy library that supports developers to implement complex requests such as request sharing, paging requests, form submissions, breakpoint uploads and others with declarative style code, allowing developers to implement high availability and high fluency request with less code, which means that you no longer need to rack your brains to write request optimization code, and no longer need to maintain request data and related status by yourself. You only need to select and use the request module, and set After setting the parameters, alova will do it for you. This improves development efficiency, application operation efficiency, and reduces server pressure.

If you have not read Quick Start, it is recommended that you read it before continuing Read this section.

In fact, the alova instance is a global request configuration, and all requests passing through this alova instance will use its configuration information. Next, follow the sample code to understand these configurations!

In the following getting started guide, we will take todos as an example, and explain alova around the needs of obtaining todo lists for different dates, viewing todo details, and creating, editing, and deleting items. . let's start!

Create an Alova instance

An alova instance is used at the beginning, all requests need to start from it. It is written like axios, the following is the simplest way to create an alova instance.

vue

import { createAlova } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import VueHook from 'alova/vue';

const alovaInstance = createAlova({
  baseURL: 'https://api.alovajs.org',
  statesHook: VueHook,
  requestAdapter: GlobalFetch()
});
Enter fullscreen mode Exit fullscreen mode

react

import { createAlova } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import ReactHook from 'alova/react';

const alovaInstance = createAlova({
  baseURL: 'https://api.alovajs.org',
  statesHook: ReactHook,
  requestAdapter: GlobalFetch()
});
Enter fullscreen mode Exit fullscreen mode

svelte

import { createAlova } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import SvelteHook from 'alova/svelte';

const alovaInstance = createAlova({
  baseURL: 'https://api.alovajs.org',
  statesHook: SvelteHook,
  requestAdapter: GlobalFetch()
});
Enter fullscreen mode Exit fullscreen mode

In the code for creating an alova instance, baseURL, statesHook, and requestAdapter are respectively specified. Now let's understand them:

  • baseURL: (optional) indicates the root path of the request. Requests sent through this alova instance will be spliced with baseURL in front, generally set to the domain name;
  • statesHook: (required) It is used to determine how to return stateful data in the use hook (such as useRequest). Currently, VueHook, ReactHook, and SvelteHook are provided to support vue, react, and svelte respectively. statesHook will help We create request-related states of different UI frameworks that can be managed by Alova, including request state loading, response data data, request error object error, etc.;
  • requestAdapter: (required) request adapter, the request adapter will be used to send all requests, the request sending module and the specific request information are decoupled. The example code uses the default provided GlobalFetch, which is supported by window.fetch for requests.

Set global request interceptor

Usually, we need to use the same configuration for all requests, such as adding token and timestamp to the request header. alova provides us with a global request interceptor, which will be triggered before the request. We can use this interceptor Set the request parameters in a unified way, which is also similar to axios.

const alovaInstance = createAlova({
  //...
  // The function parameter is a method instance, including request data such as url, params, data, headers, etc.
  // You are free to modify these data
  // highlight-start
  beforeRequest(method) {
    // Suppose we need to add token to the request header
    method.config.headers.token = 'token';
  }
  // highlight-end
});
Enter fullscreen mode Exit fullscreen mode

You can also make beforeRequest an async function.

const alovaInstance = createAlova({
  //...
  // highlight-start
  async beforeRequest(method) {
    // perform some asynchronous tasks
    //...
  }
  // highlight-end
});
Enter fullscreen mode Exit fullscreen mode

Detailed request method example introduction will be explained in the next section

Set global response interceptor

When we want to unify the parsing of response data and uniform handling of errors, we can specify a global response interceptor when creating an alova instance, which is also similar to axios. Response interceptors include interceptors for successful requests and interceptors for failed requests.

const alovaInstance = createAlova({
  //...
  // highlight-start
  // Use two items of the array to specify the interceptor for successful request and the interceptor for failed request
  responded: {
    // request success interceptor
    // When using the GlobalFetch request adapter, the first parameter receives the Response object
    // The second parameter is the method instance of the current request, you can use it to synchronize the configuration information before and after the request
    onSuccess: async (response, method) => {
      if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        // This request will throw an error when an error is thrown or a Promise instance in the reject state is returned
        throw new Error(json.message);
      }

      // The parsed response data will be passed to the transformData hook function of the method instance, and these functions will be explained later
      return json.data;
    },

    // Interceptor for request failure
    // This interceptor will be entered when the request is wrong.
    // The second parameter is the method instance of the current request, you can use it to synchronize the configuration information before and after the request
    onError: (err, method) => {
      alert(error.message);
    }
  }
  // highlight-end
});
Enter fullscreen mode Exit fullscreen mode

If you don't need to set the interceptor for request failure, you can directly pass in the interceptor function for successful request instead of setting the callback through the object.

const alovaInstance = createAlova({
  //...
  // highlight-start
  async responded(response, method) {
    // request success interceptor
  }
  // highlight-end
});
Enter fullscreen mode Exit fullscreen mode

Attention

  1. Both onSuccess and onError can be set as synchronous function or asynchronous function.
  2. The onError callback is a capture function for request errors. it will not emit onError when throw error in onSuccess. When an error is caught but no error is thrown or a Promise instance in the reject state is returned, the request will be considered successful and no response data will be obtained.
  3. In 2.0.x and previous versions, responded was misspelled as responsed, and the two have been made compatible in 2.1.0. It is recommended to use responded instead of responsed in subsequent versions.

Set the global request timeout

The following is to set the global request timeout.

// Globally set the request timeout
const alovaInstance = createAlova({
  //...
  // highlight-start
  // Request timeout time, in milliseconds, the default is 0, which means never timeout
  timeout: 50000
  // highlight-end
});
Enter fullscreen mode Exit fullscreen mode

Other information of alovajs

Why create alova?

Data requests have always been an essential part of applications. Since the birth of XMLHttpRequest, request schemes have emerged in an endless stream. Client data interaction exploration has always focused on the simplicity of requests, such as $.ajax, axios, fetch api and react-query and other request tools, the coding form is continuously developed from callback function, Promise, and then usehook. These js libraries have done a good job in request simplicity, but they only provide general functions, which means For different request scenarios such as sharing requests, paging requests, form submissions, uploading and downloading files, etc., developers still need to write complex codes themselves, which reduces development efficiency and performance cannot be guaranteed. In this era, application fluency has become more and more important.

We believe that there are simpler solutions, such as using a use hook to get and manage paging data, manage form data, and implement brokenpoint continuingly-transferring, etc. That is use different request strategies in different request scenarios to efficiently implement the request function, so that developers can code less and achieve more efficient Client-Server data interaction. This is the solution we proposed and the mission of alova.

Reasons for choosing alova

Alova is also committed to solving the problem of client network requests, but unlike other request libraries, alova chooses the direction of business scenario request strategy, and it also provides rich Advanced Features.

  • You may have been thinking about how to wrap fetch and axios. Now you no longer need to do this. alova complete complex requests with declarative style, such as request sharing, paging requests, form submissions, breakpoint uploads, etc, as well as automated cache management, request sharing, cross-component status update, etc.
  • alova is lightweight, only 4kb+, which is 30%+ of axios.
  • alova is low-coupling, you can make alova work with any UI framework in any js environment through different adapters (built-in supported UI framework is vue/react/svelte), and provides a unified experience and perfect code migration.
  • alova can also achieve a highly aggregated organization of APIs. The request parameters, cache behavior, and response data transform of each API will be in the same code block, which has great advantages for managing a large number of APIs.

For comparison with other request libraries

More framework support

Now, alova is available in vue options (vue2 and vue3), click here to view details. In the future, the following frameworks will be supported:

  • Function style such as solid/preact/qwik.
  • class style such as angular/lit/stencil.
  • options style such as native mini Program (ChinaπŸ‡¨πŸ‡³).

End

There are many runnable examples here

If you think the article is helpful to you, please don't be stingy with your likes and comments. Tell me what you think of alovajs, or ask some questions. I will try my best to answer them. Your support is the biggest motivation for my creation! Hahahahahaha...

If you want to learn more about the usage of alovajs, welcome to alova document to learn. If you also like alovajs, please star it in Github repository, which is very important to us.

Welcome to join the communication community

If you have any questions, you can join the following communication, or you can publish Discussions in github repository. If you encounter any problems, please submit it in github issues and we will solve them as soon as possible.

At the same time, you are welcome to contribute, please go to Contributing guidelines.

Top comments (0)