{"id":16823456,"url":"https://github.com/digitalbrainjs/cp-koa","last_synced_at":"2025-04-09T22:51:21.066Z","repository":{"id":57210170,"uuid":"360556511","full_name":"DigitalBrainJS/cp-koa","owner":"DigitalBrainJS","description":"Koa with cancellable middlewares support","archived":false,"fork":false,"pushed_at":"2022-02-01T18:08:04.000Z","size":570,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T00:41:38.112Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DigitalBrainJS.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-04-22T14:54:06.000Z","updated_at":"2022-12-13T18:23:50.000Z","dependencies_parsed_at":"2022-09-01T04:21:00.934Z","dependency_job_id":null,"html_url":"https://github.com/DigitalBrainJS/cp-koa","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-koa","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-koa/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-koa/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DigitalBrainJS%2Fcp-koa/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DigitalBrainJS","download_url":"https://codeload.github.com/DigitalBrainJS/cp-koa/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247721889,"owners_count":20985085,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":[],"created_at":"2024-10-13T11:08:03.288Z","updated_at":"2025-04-09T22:51:21.025Z","avatar_url":"https://github.com/DigitalBrainJS.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.com/DigitalBrainJS/cp-koa.svg?branch=master)](https://travis-ci.com/DigitalBrainJS/cp-koa)\n[![Coverage Status](https://coveralls.io/repos/github/DigitalBrainJS/cp-koa/badge.svg?branch=master)](https://coveralls.io/github/DigitalBrainJS/cp-koa?branch=master)\n![npm](https://img.shields.io/npm/dm/cp-koa)\n![npm bundle size](https://img.shields.io/bundlephobia/minzip/cp-koa)\n![David](https://img.shields.io/david/DigitalBrainJS/cp-koa)\n[![Stars](https://badgen.net/github/stars/DigitalBrainJS/cp-koa)](https://github.com/DigitalBrainJS/cp-koa/stargazers)\n\n## CP-Koa :star:\n\n`CPKoa` is an enhanced version of [Koa](https://www.npmjs.com/package/koa) with the support of cancellable middleware, \nthat can be automatically canceled when client disconnecting.\nThe package internally uses `CPromise` (provided by [c-promise2](https://www.npmjs.com/package/c-promise2))\ninstead of the native to bring the cancellation and progress capturing to the `CPKoa`. \n\nSee the [Codesandbox demo](https://codesandbox.io/s/cp-koa-readme-basic-xr2fi)\n````javascript\nconst CPKoa = require('cp-koa');\nconst {CPromise} = require('c-promise2');\n\nconst app = new CPKoa();\n\napp.use(function*(ctx, next){\n  console.log(`First middleware [${ctx.url}]`);\n  yield CPromise.delay(2000);\n  ctx.body= `Hello! [${yield next()}]`\n}).use(function*(){\n  console.log(`Second middleware`);\n  yield CPromise.delay(500);\n  return new Date().toLocaleTimeString();\n}).on('progress', (ctx, score)=\u003e{\n  console.log(`Progress: ${(score*100).toFixed(1)}%`)\n}).listen(3000);\n````\n\n````output\nFirst middleware [/]\nProgress: 25.0%\nProgress: 50.0%\nSecond middleware\nProgress: 100.0%\n````\nYou can still use ECMA async function as middlewares:\n````javascript\napp.use(function* (ctx, next) {\n  console.log(`First middleware [${ctx.url}]`);\n  yield CPromise.delay(2000);\n  ctx.body = `Hello! [${yield next()}]`\n})\n  .use(async (ctx) =\u003e {\n    console.log(`Second ECMA async middleware`);\n    await CPromise.delay(1000);\n    return new Date().toLocaleTimeString();\n  })\n  .on('progress', (ctx, score) =\u003e {\n    console.log(`Progress: ${(score * 100).toFixed(1)}%`)\n  }).listen(3000);\n````\nCPKoa's `ctx` has a `scope` property that refers to the relative `CPromise` instance. \nSince every CPromise has a `signal` property that provides `AbortController` signal (controllers creating on demand),\nyou can use it to cancel your async routines, when the parent scope cancels.\nThis allowing you to use async middlewares and functions that do not support `CPromise` out of the box. \n````javascript\napp.use(async (ctx) =\u003e {\n  console.log(`Second ECMA async middleware`);\n  await CPromise.run(function* () {\n    yield CPromise.delay(1000);\n    console.log('stage 4');\n    yield CPromise.delay(1000);\n    console.log('stage 5');\n  }).listen(ctx.scope.signal);\n})\n````\nCPKoa's ctx object has a shortcut to do this easier:\n````javascript\napp.use(async (ctx) =\u003e {\n  await ctx.run(function* () { // this async routine will be cancelled when the client disconnecting\n    yield CPromise.delay(1000);\n    console.log('stage 4');\n    yield CPromise.delay(1000);\n    console.log('stage 5');\n  });\n  ctx.body= 'Done!';\n})\n````\nCPromise provides `timeout` method, so you able to set a timeout for each middleware separately if you need to.\n````javascript\nconst app = new CPKoa();\n\napp.use(function* (ctx, next) {\n  console.log(`Start [${ctx.url}]`);\n  this.timeout(2000);\n  const response = yield cpAxios(`https://run.mocky.io/v3/7b038025-fc5f-4564-90eb-4373f0721822?mocky-delay=5s`);\n  ctx.body = `Hello! Response : [${JSON.stringify(response.data)}]`\n}).listen(3000);\n````\nThe `CPromise` chain can be marked as `atomic` - the execution of such a chain cannot be interrupted from the upper chains.\nBy default, the top chain will wait for the atomic chain to complete, or if the `detached` option has been set,\nit will continue canceling the top chain while the atomic chain continues in the background.\n````javascript\napp.use(function*(ctx, next){\n  this.atomic();// The request promise chain can not be interrupted while this sub-chain is not completed.\n  yield CPromise.delay(100);\n  console.log('stage 1');\n  yield CPromise.delay(1000);\n  console.log('stage 2');\n  yield CPromise.delay(1000);\n  console.log('stage 3');\n  ctx.body = new Date().toLocaleTimeString();\n})\n````\nSince koa-router currently do not support `CPromise` features, you have to use a workaround with `ctx.run`\ninside your routes:\n````javascript\nconst app = new CPKoa();\n\nconst router = new Router();\n\nrouter.get('/', async(ctx, next)=\u003e{\n  await ctx.run(function*(){\n    this.innerWeight(3); // total progress score\n    yield CPromise.delay(1000);\n    console.log('stage 1');\n    yield CPromise.delay(1000);\n    console.log('stage 2');\n    yield CPromise.delay(1000);\n    console.log('stage 3');\n    ctx.body= \"Root page\"\n  });\n})\n\napp\n  .use(router.routes())\n  .use(router.allowedMethods())\n  .on('progress', (ctx, score) =\u003e {\n    console.log(`Progress: ${(score * 100).toFixed(1)}%`)\n  }).listen(3000);\n````\n\n## Related projects\n- [c-promise2](https://www.npmjs.com/package/c-promise2) - promise with cancellation and progress capturing support\n- [use-async-effect2](https://www.npmjs.com/package/use-async-effect2) - cancel async code in functional React components\n- [cp-axios](https://www.npmjs.com/package/cp-axios) - a simple axios wrapper that provides an advanced cancellation api\n- [cp-fetch](https://www.npmjs.com/package/cp-fetch) - fetch with timeouts and request cancellation\n\n## API Reference\n\n## Classes\n\n\u003cdl\u003e\n\u003cdt\u003e\u003ca href=\"#CPKoaApplication\"\u003eCPKoaApplication\u003c/a\u003e ⇐ \u003ccode\u003eKoa\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003c/dd\u003e\n\u003c/dl\u003e\n\n## Members\n\n\u003cdl\u003e\n\u003cdt\u003e\u003ca href=\"#E_CLIENT_DISCONNECTED\"\u003eE_CLIENT_DISCONNECTED\u003c/a\u003e : \u003ccode\u003estring\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eRequest cancellation reason for cases when the user was disconnected\u003c/p\u003e\n\u003c/dd\u003e\n\u003cdt\u003e\u003ca href=\"#E_SERVER_CLOSED\"\u003eE_SERVER_CLOSED\u003c/a\u003e : \u003ccode\u003estring\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eRequest cancellation reason for cases when the server is closing\u003c/p\u003e\n\u003c/dd\u003e\n\u003c/dl\u003e\n\n## Functions\n\n\u003cdl\u003e\n\u003cdt\u003e\u003ca href=\"#isCanceledError\"\u003eisCanceledError(thing)\u003c/a\u003e ⇒ \u003ccode\u003eboolean\u003c/code\u003e\u003c/dt\u003e\n\u003cdd\u003e\u003cp\u003eCheck whether the object is an CanceledError instance\u003c/p\u003e\n\u003c/dd\u003e\n\u003c/dl\u003e\n\n\u003ca name=\"CPKoaApplication\"\u003e\u003c/a\u003e\n\n## CPKoaApplication ⇐ \u003ccode\u003eKoa\u003c/code\u003e\n**Kind**: global class  \n**Extends**: \u003ccode\u003eKoa\u003c/code\u003e  \n**Api**: public  \n\n* [CPKoaApplication](#CPKoaApplication) ⇐ \u003ccode\u003eKoa\u003c/code\u003e\n    * [.use(middleware, [options])](#CPKoaApplication+use) ⇒ [\u003ccode\u003eCPKoaApplication\u003c/code\u003e](#CPKoaApplication)\n    * [.close([timeout])](#CPKoaApplication+close) ⇒ \u003ccode\u003eCPromise\u003c/code\u003e\n\n\u003ca name=\"CPKoaApplication+use\"\u003e\u003c/a\u003e\n\n### cpKoaApplication.use(middleware, [options]) ⇒ [\u003ccode\u003eCPKoaApplication\u003c/code\u003e](#CPKoaApplication)\nAdd middleware to the app\n\n**Kind**: instance method of [\u003ccode\u003eCPKoaApplication\u003c/code\u003e](#CPKoaApplication)  \n\n| Param | Type | Description |\n| --- | --- | --- |\n| middleware | [\u003ccode\u003eCPKoaMiddleware\u003c/code\u003e](#CPKoaMiddleware) |  |\n| [options] | \u003ccode\u003eObject\u003c/code\u003e |  |\n| [options.scopeArg] | \u003ccode\u003eBoolean\u003c/code\u003e | pass the relative CPromise scope to the middleware as the first argument |\n\n\u003ca name=\"CPKoaApplication+close\"\u003e\u003c/a\u003e\n\n### cpKoaApplication.close([timeout]) ⇒ \u003ccode\u003eCPromise\u003c/code\u003e\nCancel all requests with timeout and close running http server\n\n**Kind**: instance method of [\u003ccode\u003eCPKoaApplication\u003c/code\u003e](#CPKoaApplication)  \n\n| Param | Type | Default |\n| --- | --- | --- |\n| [timeout] | \u003ccode\u003enumber\u003c/code\u003e | \u003ccode\u003e10000\u003c/code\u003e | \n\n\u003ca name=\"E_CLIENT_DISCONNECTED\"\u003e\u003c/a\u003e\n\n## E\\_CLIENT\\_DISCONNECTED : \u003ccode\u003estring\u003c/code\u003e\nRequest cancellation reason for cases when the user was disconnected\n\n**Kind**: global variable  \n\u003ca name=\"E_SERVER_CLOSED\"\u003e\u003c/a\u003e\n\n## E\\_SERVER\\_CLOSED : \u003ccode\u003estring\u003c/code\u003e\nRequest cancellation reason for cases when the server is closing\n\n**Kind**: global variable  \n\u003ca name=\"isCanceledError\"\u003e\u003c/a\u003e\n\n## isCanceledError(thing) ⇒ \u003ccode\u003eboolean\u003c/code\u003e\nCheck whether the object is an CanceledError instance\n\n**Kind**: global function  \n\n| Param | Type |\n| --- | --- |\n| thing | \u003ccode\u003e\\*\u003c/code\u003e | \n\n\u003ca name=\"CPKoaCtx\"\u003e\u003c/a\u003e\n\n## ~CPKoaCtx : \u003ccode\u003eObject\u003c/code\u003e\n**Kind**: inner typedef  \n**Properties**\n\n| Name | Type | Description |\n| --- | --- | --- |\n| run | \u003ccode\u003efunction\u003c/code\u003e | promisify and run async function (ECMA async function, generator or callback-styled function) |\n| scope | \u003ccode\u003eCPromise\u003c/code\u003e | ref to the relative CPromise scope |\n\n\u003ca name=\"CPKoaMiddleware\"\u003e\u003c/a\u003e\n\n## ~CPKoaMiddleware : \u003ccode\u003eGeneratorFunction\u003c/code\u003e \\| \u003ccode\u003efunction\u003c/code\u003e\n**Kind**: inner typedef  \n\n| Param | Type |\n| --- | --- |\n| ctx | [\u003ccode\u003eCPKoaCtx\u003c/code\u003e](#CPKoaCtx) | \n| next | \u003ccode\u003efunction\u003c/code\u003e | \n\n\n## License\n\nThe MIT License Copyright (c) 2021 Dmitriy Mozgovoy robotshara@gmail.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\nPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdigitalbrainjs%2Fcp-koa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdigitalbrainjs%2Fcp-koa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdigitalbrainjs%2Fcp-koa/lists"}