天天看點

JS中間件封裝api調用處理過程,解耦一堆複雜操作

定義中間件對象

class Middleware {
    constructor({ core, params }) {
        // 傳入的封裝axios
        this.core = core;
        // 傳入的axios參數
        this.params = params;
        // 存放鍊式調用的中間件函數
        this.cache = [];
    }
    use(fn) {
        if (typeof fn !== "function") {
            throw "middleware must be a function";
        }
        this.cache.push(fn);
        return this;
    }
    next(data) {
        if (this.middlewares && this.middlewares.length > 0) {
            var ware = this.middlewares.shift();
            ware.call(this, this.next.bind(this), data);
        }
        return data;
    }
    async go() {
        // 請求擷取資料,以備後序程式使用
        let result = await this.core(this.params);
        //複制函數,待執行
        this.middlewares = this.cache.map(function(fn) {
            return fn;
        });
        // 向後傳遞參數,中間插件模型處理流程資料
        this.next(result);
    }
}      

使用

// 導入參數
var onion = new Middleware({core: request, params});
onion.use(function (next, data) {
    console.log(1);
    console.log(data);
    // 向後傳遞資料
    next(data);
    console.log("1結束");
});
onion.use(function (next, data) {
    console.log(2);
    console.log(data);
    // 向後傳遞資料
    next(data);
    console.log("2結束");
});
onion.use(function (next, data) {
    console.log(3);
    console.log(data);
    console.log("3結束");
});
// 上一步沒有調用next,後面的函數都不執行
onion.use(function (next, data) {
    console.log(4);
    next(data);
    console.log("4結束");
});
onion.go();
// 1
// {a: 1, b: 2}
// 2
// {a: 1, b: 2, c: 3}
// 3
// {a: 1, b: 2, c: 3, d: 4}
// 3結束
// 2結束
// 1結束
// {a: 1, b: 2, c: 3, d: 4}      

配合API接口資料傳回後的操作函數

function handleStatus(next, res) {
    console.log(res);
    next(res);
}
function handleAuth(next, res) {
    console.log(res);
    next(res);
}
function handlePosition(next, res) {
    console.log(res);
    next(res);
}
function handleForbiddenList(next, res) {
    console.log(res);
    next(res);
}
function handleLoad(next, res) {
    console.log(res);
    next(res);
}      

通過中間件以此注冊

// 導入參數
var onion = new Middleware({core: request, params});
onion.use(handleStatus);
onion.use(handleAuth);
onion.use(handlePosition);
onion.use(handleForbiddenList);
onion.use(handleLoad);
onion.go();
// 函數裡面可以用異步函數,擷取到這個流程處理完的值
// let res = await onion.go();      
api

繼續閱讀