Skip to content

Commit c19b4e9

Browse files
🤖 Merge PR DefinitelyTyped#74687 [@types/koa]: add custom AsyncLocalStorage support to Application constructor by @kshitijanurag
1 parent 5348a91 commit c19b4e9

File tree

2 files changed

+38
-16
lines changed

2 files changed

+38
-16
lines changed

‎types/koa/index.d.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,7 @@ declare class Application<
465465
* @param {number} [options.subdomainOffset] Subdomain offset
466466
* @param {string} [options.proxyIpHeader] Proxy IP header, defaults to X-Forwarded-For
467467
* @param {number} [options.maxIpsCount] Max IPs read from proxy IP header, default to 0 (means infinity)
468-
* @param {boolean} [options.asyncLocalStorage] Enable AsyncLocalStorage
468+
* @param {boolean|AsyncLocalStorage} [options.asyncLocalStorage] Pass `true` or an instance of `AsyncLocalStorage` to enable async local storage
469469
*/
470470
constructor(options?: {
471471
env?: string | undefined;
@@ -474,7 +474,7 @@ declare class Application<
474474
subdomainOffset?: number | undefined;
475475
proxyIpHeader?: string | undefined;
476476
maxIpsCount?: number | undefined;
477-
asyncLocalStorage?: boolean | undefined;
477+
asyncLocalStorage?: boolean | AsyncLocalStorage<ContextT> | undefined;
478478
});
479479

480480
/**
Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,41 @@
11
import Koa = require("koa");
2+
import assert from "node:assert/strict";
3+
import { AsyncLocalStorage } from "node:async_hooks";
24

3-
const app = new Koa({
4-
env: "abc",
5-
keys: ["im a newer secret", "i like turtle"],
6-
proxy: true,
7-
subdomainOffset: 2,
8-
proxyIpHeader: "XYZ-Forwarded-For",
9-
maxIpsCount: 2,
10-
asyncLocalStorage: true,
11-
});
5+
{
6+
const app = new Koa({
7+
env: "abc",
8+
keys: ["im a newer secret", "i like turtle"],
9+
proxy: true,
10+
subdomainOffset: 2,
11+
proxyIpHeader: "XYZ-Forwarded-For",
12+
maxIpsCount: 2,
13+
asyncLocalStorage: true,
14+
});
1215

13-
app.use(ctx => {
14-
ctx.body = "Hello World";
15-
});
16+
app.use(ctx => {
17+
ctx.body = "Hello World";
18+
});
1619

17-
app.listen(3000);
20+
app.listen(3000);
21+
}
1822

19-
const server = app.listen();
23+
{
24+
const asyncLocalStorage = new AsyncLocalStorage<Koa.Context>();
25+
const app = new Koa({ asyncLocalStorage });
26+
27+
assert(app.currentContext === undefined);
28+
29+
app.use(async (ctx, next) => {
30+
callSomeFunction();
31+
ctx.body = "ok";
32+
await next();
33+
});
34+
35+
function callSomeFunction() {
36+
const ctx = asyncLocalStorage.getStore();
37+
assert(ctx === app.currentContext);
38+
}
39+
40+
app.listen();
41+
}

0 commit comments

Comments
 (0)