Method instance of alovajs, a request strategy library

Scott Hu - Nov 2 '23 - - Dev Community

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.

Overview about method instance

In alova, each request corresponds to a method instance, which describes the url, request header, request parameters, and request behavior parameters such as response data processing and cache data processing. Through the method instance, you can experience a unified user experience in any js environment, and it can run normally with very few changes. At the same time, the method instance puts the request parameters and request behavior parameters together, which is more convenient for api managed, rather than scattered across multiple code files.

create instance

The creation of a method instance is also very similar to the request sending function of axios. You need to create method instance by alova instance created in last term. Let's first create a Method instance to get the todo list.

// Create a Get instance to describe the information of a Get request
const todoListGetter = alovaInstance.Get('/todo/list', {
  // request header
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  // The params parameter will be spliced after the url in the form of?
  params: {
    userId: 1
  }
});
Enter fullscreen mode Exit fullscreen mode

Then create a POST request Method instance to submit the todo item, but now the second param is the request body.

// Create a Post instance
const createTodoPoster = alovaInstance.Post(
  '/todo/create',
  // The second parameter is the http body data
  {
    title: 'test todo',
    time: '12:00'
  },
  // The third parameter is request configuration related information
  {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    params: {
      //...
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

⚠️ Note: The Method instance only saves the information needed for the request, it does not send the request, but needs to send the request through the use hook (will be explained in detail later), or call methodInstance.send to send request, which is different from axios.

Set request-level timeout

The global request timeout applies to all Method instances, but many times we need to set different timeouts according to special requests. At this time, we can set the request-level timeout, which will override the global timeout parameter

// Request timeout at the request level
const todoListGetter = alovaInstance.Get('/todo/list', {
  //...
  // highlight-start
  timeout: 10000
  // highlight-end
});
Enter fullscreen mode Exit fullscreen mode

Request behavior parameters

In addition to setting request parameters, method instances can also set request behavior parameters. The following are the supported request behavior parameters, which will also be explained in detail in subsequent chapters.

Name Description
name method instance name, which is generally used to match method instances
transformData Set the response data conversion function, see Convert Response Data
localCache Set the request-level cache mode, see cache mode
enableDownload Enable download progress information, see Download/Upload Progress
enableUpload Enable upload progress information, see Download/Upload Progress
hitSource Cache auto-invalidation settings, see Auto-invalidate cache for details
shareRequest Sharing request, see Share Request

Set the parameters supported by the request adapter

In the Chapter about understanding alova instances, we have built-in and recommended GlobalFetch as alova's request adapter. It will internally send requests through the fetch function. At this time, you can also Any parameter supported by fetch can be configured on the method instance, but we recommend setting request parameters using the fields mentioned above.

const todoListGetter = alovaInstance.Get('/todo/list', {
  // ...
  // highlight-start
  credentials: 'same-origin',
  referrerPolicy: 'no-referrer',
  mode: 'cors'
  // highlight-end
});
Enter fullscreen mode Exit fullscreen mode

This is easy to understand, that is, in addition to unified parameters such as request parameters and request behavior parameters, you can also set any parameters supported by the request adapter. In the extension, we also provide XMLHttpRequest Adapter, axios Adapter, Uniapp Adapter, Taro adapter etc. Each adapter also has the parameters they support.

Request method type

Alova provides abstract instances of seven request methods including GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH. For specific usage methods, please read Request Method Details.

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.

. . . . . . . . . . . . . . . . . . . . . . . . .