{"id":26208366,"url":"https://github.com/jiefancis/simplekoa","last_synced_at":"2026-05-02T08:31:24.864Z","repository":{"id":168178663,"uuid":"364482289","full_name":"jiefancis/simpleKoa","owner":"jiefancis","description":"koa的实现与洋葱模型","archived":false,"fork":false,"pushed_at":"2021-05-14T14:40:41.000Z","size":9,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-12-19T17:26:42.917Z","etag":null,"topics":["koa","node"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jiefancis.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-05-05T06:32:13.000Z","updated_at":"2022-05-10T06:08:05.000Z","dependencies_parsed_at":null,"dependency_job_id":"1e2d189c-baf7-4145-b86c-53aa7cb07dc0","html_url":"https://github.com/jiefancis/simpleKoa","commit_stats":null,"previous_names":["jiefancis/simplekoa"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/jiefancis/simpleKoa","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jiefancis%2FsimpleKoa","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jiefancis%2FsimpleKoa/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jiefancis%2FsimpleKoa/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jiefancis%2FsimpleKoa/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jiefancis","download_url":"https://codeload.github.com/jiefancis/simpleKoa/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jiefancis%2FsimpleKoa/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32528102,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-02T01:12:54.858Z","status":"online","status_checked_at":"2026-05-02T02:00:05.923Z","response_time":132,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["koa","node"],"created_at":"2025-03-12T06:28:34.890Z","updated_at":"2026-05-02T08:31:24.845Z","avatar_url":"https://github.com/jiefancis.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## 洋葱模型产生的背景\nkoa2与express最大的区别是：koa2中间件执行机制使用的是洋葱模型；而express框架中，中间件则是线性执行，每一个中间件执行完后，要么交给下一个中间件，要么返回response。只要请求离开了，中间件就无法再次获取这个请求及处理。\n\n\n## 为什么要使用洋葱模型？\n当我们使用koa进行开发的时候，因为读取数据库或是http请求等都是异步请求，所以我们为了保证洋葱模型会使用号称异步终极解决方案的async/await。\n\n## 洋葱模型的实现原理\n洋葱模型的灵魂之处在于：Array.prototype.reduce()；如果对reduce不熟悉，可以去mdn回顾一下reduce的使用。compose的实现核心是：将各个函数作为前一个function的next参数传递过去\n\n一、洋葱模型的同步实现：\n\n    var app = {\n        middlewares: [],\n        use(fn){\n            app.middlewares.push(fn)\n        },\n        compose(){\n            function dispatch(i){\n                if(i === app.middlewares.length) return\n                const fn = app.middlewares[i]\n                // 将每一个函数作为前一个函数的next参数传递。\n                return fn(() =\u003e dispatch(i+1))\n            }\n            dispatch(0)\n        }\n    }\n    // next是() =\u003e dispatch(i+1)的引用\n    app.use(next =\u003e { \n        console.log('1--before')\n        next()\n        console.log('1--after')\n    })\n    app.use(next =\u003e {\n        console.log('2--before')\n        next()\n        console.log('2--after')\n    })\n    app.use(next =\u003e {\n        console.log('3--before')\n        next()\n        console.log('3--after')\n    })\n    app.compose()\n\n    // 运行结果为：\n    //     1--before\n    //     2--before\n    //     3--before\n    //     3--after\n    //     2--after\n    //     1--after\n    \n    \n    \n二、洋葱模型的异步实现（代码来源于koa-compose）\n    \n        查看了koa-compose源码，其中compose的源代码只有寥寥几十行，对比同步实现的区别在于异步方式引入了async/await支持。代码实现如下\n        \n            function compose(middlewares){\n                // 容错处理\n                if(!Array.isArray(middlewares)) throw new Error('middlewares must be an  array!')\n                for(const fn of middlewares) {\n                    if(typeof fn !== 'function') {\n                        throw new Error('middleware must be a function!')\n                    }\n                }\n                \n                return function (context, next){\n                    const index = -1\n                    return dispatch(0)\n                    function dispatch(i) {\n                        if(i \u003c= index) return Promise.reject(new Error('next() called multiple times'))\n                        index = i\n                        \n                        const fn = middlewares[i]\n                        if(i === middlewares.length) fn = next\n                        if(!fn) return Promise.resolve()\n\n                        try{ // 异步\n                            return Promise.resolve(fn(context, dispatch.bind(null, i+1)))\n                        }catch(err) {\n                            return Promise.reject(err)\n                        }\n                    }\n                }\n            }\n        \n    \n三、reduce实现compose\n        \n        得益于reduce的特性，reduce()可以作为一个高阶函数，用于函数的组合compose。实现将后一个函数作为前一个函数的参数传递。\n\n        function add5(x) {\n            return x + 5;\n        }\n        \n        function div2(x) {\n            return x / 2;\n        }\n        \n        function sub3(x) {\n            return x - 3;\n        }\n        \n        const chain = [add5, div2, sub3].reduce((a, b) =\u003e (...args) =\u003e a(b(...args)))\n        chain(1) === 4\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjiefancis%2Fsimplekoa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjiefancis%2Fsimplekoa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjiefancis%2Fsimplekoa/lists"}