DEV Community

Cover image for 3 months later, I optimized request code generation to the extreme
Scott Hu
Scott Hu

Posted on

3 months later, I optimized request code generation to the extreme

Have you ever heard of the automatic request code generation solution? Yes, that's right, it's generated by the openapi specification, and I always feel that something is missing.

After 3 months of research, I have simplified the front-end and back-end collaboration process into one step!

Usually, the front-end and back-end collaboration is a tedious task. Usually we may have such a process:

  1. The back-end notifies the front-end "xxx interface is ready"

  2. First look through the api document to find the newly added api

  3. Go back to your own code and define all new api call functions

  4. If you use TS, you have to add type definitions manually

  5. In different pages, select the corresponding api call function

  6. Introduce the call function

  7. Write complex call logic, such as paging and controlling the page number parameter

We have removed all the 123467 above, and even eliminated the intermediate api document link, allowing you to check and call the api in the editor, which may change your future development method.

Let me explain it in detail.

Automatic generation

Automatically generating API call code according to the openapi specification should be a commonplace, and my solution is to use the VSCode plug-in. Whether you use ESModule, CommonJS or TypeScript, click the generate button in the lower right corner of the editor, it will automatically generate the corresponding standard interface call code and the corresponding response type according to the project type. Whether in js or ts projects, you can experience the complete code prompt function.

Generated code Contains the following content:

Image description

  1. apiDefinitions.js is used to record the generated api path and request method.
  2. createApis.js uses proxy to dynamically create call functions based on apiDefinitions.js, which can reduce a lot of template code.
  3. globals.d.ts provides complete code prompt function.
  4. index.js is used for user-defined configuration.

This cuts off step 34 in the process.

Then we can also set a timer to check the update status of the openapi file. If there is an update, we will immediately remind you to ensure that you always use the latest api definition. This saves the backend partner from notifying you of api updates, and eliminates step 1 in the process.

Now the process is as follows:

  1. The backend notifies the frontend "xxx interface is ready"

  2. First look through the api document to find the newly added api

  3. Go back to your own code and define all new api call functions

  4. If you use TS, you have to add type definitions manually

  5. In different pages, select the corresponding api call function

  6. Introduce the call function

  7. Write complex call logic, such as paging and controlling the number of pages

Check and use the API in the editor

In order to eliminate step 2, we really racked our brains, so let's just move the api document to the editor and copy the parameters according to the description when you use the interface.

The following is a demonstration of a js project without any additional configuration.

Image description

Access the interface through the global Apis, reference src/api/index in the entry file, and then you can directly access it everywhere, which eliminates step 7 again, and the editor's smart prompt displays all the information of the current api.

Image description

You can also see the prompts and descriptions of the parameters when filling in the parameters.

Image description

The response data prompt is as follows.

Image description

Find API through path

What is this? I don't know what the specific reference name is? It doesn't matter, you can also find it by using the API call path:

Image description

Find the API by description

Really can't remember anything? Then search using the keywords in the API description:

Image description

At this point, steps 2 and 6 are also done:

  1. The backend notifies the frontend that "xxx interface is ready"
  2. First look through the api document to find the newly added api
  3. Go back to your own code and define all new api call functions
  4. If you use TS, you have to add type definitions manually
  5. In different pages, select the corresponding api call function
  6. Introduce calling function
  7. Write complex calling logic, for example, paging also needs to control the number of pages

Request strategy modules

How to solve step 7? Of course, encapsulate the calling logic according to different usage scenarios. Although there seem to be many scenarios, let's encapsulate the commonly used ones first, so there are the following encapsulations, which we call "request strategy module" because it is not only encapsulation, but also many performance optimizations.

Here are some simple examples, such as paging request:

const { loading, error, data, page, pageSize, total } = usePagination(
  (page, size) =>
    alova.Get("/api/user/list", {
      params: { page, size },
    })
);
Enter fullscreen mode Exit fullscreen mode

Form submission:

const {
  // Submission status
  loading: submiting,
  // Responsive form data
  form,
  // Submission data function
  send: submit,
} = useForm((formData) => formSubmit(formData), {
  // Initialize form data
  initialForm: {
    name: "",
    cls: "1",
  },
});
Enter fullscreen mode Exit fullscreen mode

Monitor request:

const { loading, data } = useWatcher(
  // State change will trigger this function once
  () => filterTodoList(userId.value),

  // Array of monitored states
  [userId]
);
Enter fullscreen mode Exit fullscreen mode

Now, it is finally simplified to only one step.

  1. The backend notifies the frontend that "xxx interface is ready"
  2. First look through the api document to find the newly added api
  3. Go back to your own code and define the call function for all new apis
  4. If you use TS, you have to add type definitions manually
  5. In different pages, select the corresponding api call function
  6. Introduce the call function
  7. Write complex call logic, such as paging and controlling the number of pages

The last easter eggs

At this point, I believe you have already felt the convenience of this plug-in, right? This is actually a VSCode plug-in tailored for alova!

Our easter egg is that alova has finally ushered in a major upgrade to 3.0, redesigning the underlying architecture and comprehensively refactoring. Now it can be used completely in the client and server. In addition, in order to make it easier to use, this upgrade has abandoned 10 configurations and 9 optimizations. If you think alova is good, please star us on Github.

Visit the official website of alovajs for more details: alovajs official website.

And this plug-in is not just an ordinary development tool, but it maximizes the convenience of alova. Through this plug-in, we have brought the user experience of alova to a whole new level, truly realizing the goal of "as simple as calling a local function".

However, our team is now conducting the final optimization and testing of this plug-in, which will be released in the near future. Good things are always worth waiting for. You are also welcome to tell us your thoughts, complaints or suggestions in the comment area.

If you are an alova user, or are interested in experiencing our project, you can join our WeChat group to get the latest progress at the first time, and you can also communicate directly with the development team and put forward your ideas and suggestions.

After joining the communication community, you will get:

  1. The latest news about plugins and alova
  2. Exchange usage experience with other developers
  3. Make suggestions or feedback directly to the development team
  4. Possible internal testing opportunities

If you have any questions, you can join the following group chat for consultation, or post Discussions in the github repository. If you encounter any problems, please submit them in github issues, and we will solve them as soon as possible.

You are also welcome to contribute. Please go to the Contribution Guide

Top comments (0)