This article is updated synchronously on my Github by clicking to go. It will show you how to intercept an AXIos request and validate the request parameters to prevent invalid values from being submitted. You can also use the Async-Validator tool to validate form parameters. I’ve used it to encapsulate Vue form components before, so I’ll write a tutorial on how to encapsulate your own Vue components later.

Since I’ve been developing in Typescript, I submit files with a.ts suffix. You can also modify the suffix and remove the type declaration;

Document describing

Root: | - the validator# Check method
 |--axios # AXIos encapsulates the request // intercept configuration
 |    |--config.ts # Axios interceptor configuration file
 |    |--service,ts # axios requests the configuration file

Copy the code

For a long time, when submitting a request, we often encountered a situation where the submitted parameters did not match the background requirements; This is a wasted request. In particular, in the case of slow network, it takes too long to return, which is very bad for users’ experience.

use

API request

    // api
    import service from 'path/service';
    import {
        validate
    } from 'path/validator';

    // When a request parameter is checked
    function anyRequest(id) {
        // 
        return service.get({
            url: `path/${id}`
        }, {
            fileds: {
                id: 'Parameter name to verify'
            },
            rules: {
                id: [validate.isRequired],
            }
        });
    }
    
    // Verify multiple request parameters
    function anyRequest(id, obj) {
        // 
        return service.post({
            url: `path/${id}`.data: {
                name: 'Echi'.age: '26'}}, {fileds: {
                id: 'Parameter name to verify'.obj: 'This is an object.'
            },
            rules: {
                id: [validate.isRequired],
                obj: {
                    ...validate.isObject,
                    fileds: {
                        name: [validate.isRequired],
                        age: [validate.isRequired],
                    }
                }
            }
        });
    }

Copy the code

Calibration method and parameter setting

    // validator
    import AsyncValidator from 'async-validator';

    * @export * @param [Object] [fileds={key: Value}] Field to be verified * @param [Object] [rules={key: validator}] // Verification rule * @returns void */
    export default function requestValidator(fileds = {}, rules = {}) {
        return new Promise((resolve, reject) = > {
            const validator = new AsyncValidator(rules);
            validator.validate(fileds, {
                firstFields: true
            }, (errors, data) => {
                conststatus = ! errors ?'success' : 'error';
                const message = errors ? errors[0].message : ' ';
                if (status === 'success') {
                    resolve({
                        status,
                        message,
                        data
                    });
                } else {
                    console.warn('Current parameter verification fails, error message:${message}`);
                    reject({
                        status,
                        message,
                        data,
                        isValid: true}); }}); }); }// Check rules
    See https://github.com/yiminghe/async-validator / / field extension
    export const validate = {
        / / mandatory
        isRequired: {
            required: true
        },
        // String validation
        isString: {
            type: 'string'
        },
        // Object verification
        isObject: {
            type: 'object'
        },
        // Array check
        isArray: {
            type: 'array'
        },
        // Numeric verification
        isNumber: {
            type: 'number'}};Copy the code

Encapsulate the AXIOS request

    // service
    import axios from './config';
    import requestValidator from '.. /validator';

    // HTTP utility class
    export default class Http {
    public static asyncrequest(params: any, descriptor ? : any) {// Add request interception validation
        if(descriptor ! = =undefined) {
            let fileds = descriptor.fileds || {};
            let rules = descriptor.rules || {};
            await requestValidator(fileds, rules);
        }
        return await axios(params);
    }

    /** * get * @param [url] address * @param [data] data * @returns Promise */
    public staticget(req: any, descriptor ? : any): any {return this.request({
            method: 'GET'.url: ` /${req.url}`.params: req.data,
        }, descriptor);
    }

    /** * put * @param [url] address * @param [data] data * @returns Promise */
    public staticput(req: any, descriptor ? : any): any {return this.request({
            method: 'PUT'.url: ` /${req.url}`.data: req.data,
        }, descriptor);
    }

    /** * post * @param [url] address * @param [data] data * @returns Promise */
    public staticpost(req: any, descriptor ? : any): any {return this.request({
            method: 'post'.url: ` /${req.url}`.data: req.data,
        }, descriptor);
    }

    /** * delete * @param [url] address * @param [data] data * @returns Promise */
    public static delete(req: any, descriptor ? : any): any {return this.request({
            method: 'DELETE'.url: ` /${req.url}`.params: req.data, }, descriptor); }}Copy the code

Finally, thank you for watching, if you have any questions or a better way to write, welcome to share ~

Link to this article: juejin.cn/user/729731… Copyright Notice: This article is licensed BY @BY-NC-SA unless otherwise stated. Reprint please indicate the source!