I checked the last post. Two months ago. I haven’t updated it in a long time. There is also not much of a deepening in technical depth. Let’s do a cliche this time. API service encapsulation. This is the code that I’ve been working on over the years.
Features:
1. Support multiple different microservices (core)
2. Centralized configuration center
3. Simplify development process and optimize development experience
4. Decoupled and portable
How do we encapsulate interface services
Let me tease you about what’s wrong with all of this. I’ve tried it all, right
1, add interface blocking service, what duplicate interface to prevent commit
A lot of articles have been written on Top of Axios, repackaged based on axios’s own API. Disadvantages aside. In itself, the biggest problem when you try to block duplicate routes is that as the project gets bigger and bigger, you use one interface in two places on one page and I ask what do you do?
2. Anti-shake processing, optimize business code, avoid multiple instantaneous submission
The main purpose of this encapsulation is for us to avoid committing more than twice in an instant with action buttons like save. Loading, for example, is not 100% safe.
But this is because your anti-shake encapsulation is global, so when there are more than two apis at a time, only the first API is valid. No other API can request it. Of course, if you want to create an API in class mode, you don’t want to have to new an object.
3. Use rest as a back-end service (PS: LJ)
I really think you are very S of this, the purpose of our packaging is to save the amount of code, not let you increase the amount of code
Post,get,delete all write a function, you are not busy
4. These programs seem to be common in the community
For now.
Why encapsulate API services?
1. Let’s write less code
To save code, you guys? My pet pester is a project that encapsulates nothing, including direct use of axios’s direct API. You are fine for your individual business environment, but each business environment encapsulates a lot of work.
What’s more, what a lot of novices and old hands are doing is just writing things down. Direct is just using. After the project let you change something crazy, want to unified management or some global monitoring and so on, alas……
2. Business pain points
As the company gets bigger you don’t just have one back-end service, you have to have two or more. However, the return value of each service may not be correct. Do you have to judge them as you actually write them?
Do you repackage every time you go to mobile, PC, applets, etc.? And then have to be updated every time for that service? It’s painful.
There are also some projects that need to be directly loaded waiting interface, write separately is also code amount
Third, code parsing
Project address: github.com/ht-sauce/to…
The MD file is not updated in time. Forgive me,
The first is the directory structure
1, the config. Js
This is nothing special it’s just a pre-configuration for different microservices, right
2. Base files
At its core, Axiosajax.js, tips.js is designed to pull out tips globally. A lot of places need to be used
Code parsing
As you can see, it’s actually very simple. It’s basically wrapping axios first, so you should know the parameters. A code saving operation is done here, and emelent-UI loading is added
The core purpose here is to decouple axios from the aspects THAT I’ll use later on, such as porting to a applet environment. That frees up my core API part, which is critical.
Import axios from 'axios' import {Loading} from 'elemental-ui' // axios function encapsulates const ajax = ({url = ", Loading = false, BaseURL = ", data = {}, headers = {' content-type ': 'application/json; Charset = utF-8 '}, responseType = 'get', timeout = 30 * 1000, responseType = 'json', Can be 'arrayBuffer ', 'blob', 'document', 'json', 'text', 'stream'}) => {// let loadingInstance = "if (loading! == false) { loadingInstance = Loading.service({ lock: true, text: loading ! == true ? Loading: 'Loading... ', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.5)',})} const posts = ['put', 'post', 'patch'] Err) => {method = method.tolocalelowerCase (); // Set the headers to lower case ({url: url, baseURL: baseURL, headers: headers, method: method, [posts.includes(method) ? 'data' : 'params']: data, timeout: timeout, responseType, }) .then((response) => { loadingInstance && loadingInstance.close() suc(response) }) .catch((e) => { loadingInstance && loadingInstance.close() err(e) }) }) } export { ajax }Copy the code
3. Couplingajax.js parsing
I’m not going to post all the code here. Let me tell you what we did here.
The first is the input part
1. Opt parameters
The special parameters are file,isResponse, and reLogin
File is special because file is a separate file mode. Since the files of the project require password verification to be downloaded, we need to use the file parameter. In the case of file download mode, we do not need to deal with the normal business process.
IsResponse because I’m actually going to optimize the use of this code, and we know that we need data.data when we get the return parameter. I’ll skip this step and get it for you ahead of time. So that saves a little bit of code. But sometimes special cases require a complete return structure, customizing information based on error codes or other fields on the back end. Then you need to let go of that feature
ReLogin is very simple. The interface requires the authorization password. If the password fails, you need to jump to the login page
Opt. error: the default value is true. When an interface error message is displayed on the backend, a unified encapsulation message is displayed. You can turn this off by passing false. You can also pass in a string to change the prompt to the one you want
The same is true for opt.success and error
2. The middle part of the screenshot
Prefix = ", // Route prefix, which will be used as the prefix of the micro service to be concatenated to the front of each route, CodeField = 'success', // codeNum = true, // msgField = 'message', TipsCode = 'errorCode', // errorCodeCopy the code
Prefix is special. We’ll see how to use index in a second, okay
4, index.js entry file parsing
This file is very simple, mainly to let you see what prefix is used
5. Use apis files, and divide folders or files according to microservices
File and FIL parameter usage and basic configuration based on microservices
6, use,
Import service from '@/services' async test() {try {const res = await service.nbs. Ceshi ({url = '', BaseURL: '', // Data: {}, // Get or post headers: { 'Content-Type': 'application/json; Charset = utF-8 '}, // header information processing method: 'get', // access mode timeout: 30 * 1000, // interface timeout error: // Error message: string can be passed in, if the string is passed in, the error message will be the string success: }) console.log(res)} catch (e) {console.log(e)}}Copy the code
4. Summarize and give thanks
1. Generally speaking, I divided it according to different services, and achieved multiple use of a set of packages
2. Parameter configuration extraction
3. Deconstruct Axios and transplant it everywhere
Thanks for reading and like