Koa

简单实现

1.x 中间件简单实现

该实现是未深入了解 Koa、仅通过了解 Koa 的use方法后,脑补的简单实现方式。(可能与实际实现相差巨大)

主要实现了 Koa 中间件的功能,包括

  • 中间件 Generator 函数里yield next的实现
  • 中间件 Generator 函数里yield另一个中间件的实现
class App {
    constructor() {
        this.fns = [];
    }
    use(genFn) {
        this.fns.push(genFn);
    }
    next(ctx, curGen) {
        if (!curGen) {
            const curFn = this.fns[ctx.index++];
            if (!curFn) {
                return;
            }
            curGen = curFn.apply(ctx, [this.next]);
        }
        let result;
        while ((result = curGen.next()) && !result.done) {
            if (result.value === this.next) {
                ctx.gens.push(curGen);
                this.next(ctx);
                curGen = ctx.gens.pop();
            } else if (isGenerator(result.value)) {
                ctx.gens.push(curGen);
                curGen = result.value.apply(ctx, [this.next]);
                this.next(ctx, curGen);
                curGen = ctx.gens.pop();
            }
        }
    }
    emitRequest() {
        const ctx = {
            index: 0,
            gens: []
        };
        this.next(ctx);
    }
}

function isGenerator(fn) {
    return fn.constructor.name === 'GeneratorFunction';
}

const app = new App();

app.use(function*(next) {
    console.log('1');
    yield next;
    console.log('6');
});

app.use(function*(next) {
    console.log('2');
    yield function*(next) {
        console.log('3');
        yield function*(next) {
            console.log('insert');
            yield next;
        };
    };
    // yield next
    console.log('5');
});

app.use(function*(next) {
    console.log('4');
    yield;
});

app.emitRequest();

// 返回结果
// 1
// 2
// 3
// insert
// 4
// 5
// 6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

2.x 中间件简单实现

待学习