@dalet-oss/express-http-context 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2017 Steve Konves
3
+ Copyright (c) 2025 Dalet
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,86 +1,150 @@
1
- [![travis](https://img.shields.io/travis/dalet-oss/express-http-context.svg)](https://travis-ci.org/dalet-oss/express-http-context)
2
- [![coveralls](https://img.shields.io/coveralls/dalet-oss/express-http-context.svg)](https://coveralls.io/github/dalet-oss/express-http-context)
3
- [![npm](https://img.shields.io/npm/v/dalet-oss/express-http-context.svg)](https://www.npmjs.com/package/@dalet-oss/express-http-context)
4
- [![npm](https://img.shields.io/npm/dm/dalet-oss/express-http-context.svg)](https://www.npmjs.com/package/@dalet-oss/express-http-context)
5
- [![david](https://img.shields.io/dalet-oss/express-http-context.svg)](https://david-dm.org/dalet-oss/express-http-context)
1
+ [![NPM Version](https://img.shields.io/npm/v/%40dalet-oss%2Fexpress-http-context)](https://www.npmjs.com/package/@dalet-oss/express-http-context)
2
+ [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/dalet-oss/express-http-context/ci-publish.yml)](https://github.com/dalet-oss/express-http-context/actions)
6
3
 
7
- # Express HTTP Context
8
- Get and set request-scoped context anywhere. This is just an unopinionated, idiomatic ExpressJS implementation of
9
- [cls-hooked](https://github.com/Jeff-Lewis/cls-hooked) (forked from [continuation-local-storage](https://www.npmjs.com/package/continuation-local-storage)).
10
- It's a great place to store user state, claims from a JWT, request/correlation IDs, and any other request-scoped data.
11
- Context is preserved even over async/await (in node 8+).
12
4
 
13
- ## How to use it
5
+ # Express HTTP Context
6
+ Modern request-scoped storage support for Express.js, based on native Node.js
7
+ Asynchronous Local Storage. It's a great place to store user state, claims from
8
+ a JWT, request/correlation IDs, and any other request-scoped data.
9
+
10
+ This package is a drop-in replacement and has been inspired by the work done in
11
+ [express-http-context](https://github.com/skonves/express-http-context), but
12
+ with ESM support, no dependencies, and only supporting modern versions of
13
+ Node.js (+v14).
14
+
15
+ The implementation is derived from the start made in
16
+ [express-http-context2](https://github.com/artberri/express-http-context2).
17
+ We diverged to support our own implementation because the bug highlighted in
18
+ [artberri/express-http-context2#1](https://github.com/artberri/express-http-context2/issues/1)
19
+ was ultimately ignored and the repository apparently abandoned by its maintainer.
20
+
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install @dalet-oss/express-http-context
26
+ # or
27
+ yarn add @dalet-oss/express-http-context
28
+ # or
29
+ pnpm add @dalet-oss/express-http-context
30
+ ```
14
31
 
15
- Install: `npm install --save @dalet-oss/express-http-context`
16
- (Note: For node v4-7, use the legacy version: `npm install --save express-http-context@<1.0.0`)
32
+ > **Requirements**
33
+ >
34
+ > `@dalet-oss/express-http-context` is a middleware intended for `express`, so
35
+ > although it is not explicitly declared as a dependency or peer dependency, it
36
+ > requires `express` to work, as well as `@types/express` if you are using
37
+ > Typescript. The reason the dependency is not explicitly declared is that it
38
+ > could also eventually be used with `fastify` or other Node.js HTTP servers.
17
39
 
18
- Use the middleware immediately before the first middleware that needs to have access to the context.
19
- You won't have access to the context in any middleware "used" before this one.
40
+ ## Configuration
20
41
 
21
- Note that some popular middlewares (such as body-parser, express-jwt) may cause context to get lost.
22
- To workaround such issues, you are advised to use any third party middleware that does NOT need the context
23
- BEFORE you use this middleware.
42
+ Use the middleware immediately before the first middleware that needs to have access to the context. You won't have access to the context in any middleware "used" before this one.
24
43
 
25
- ``` js
26
- var express = require('express');
27
- var httpContext = require('express-http-context');
44
+ ```js
45
+ const express = require('express')
46
+ const httpContext = require('@dalet-oss/express-http-context')
28
47
 
29
- var app = express();
30
- // Use any third party middleware that does not need access to the context here, e.g.
48
+ const app = express()
49
+ // Use any third party middleware that does not need to access the context here, e.g.
31
50
  // app.use(some3rdParty.middleware);
32
- app.use(httpContext.middleware);
33
- // all code from here on has access to the same context for each request
51
+ app.use(httpContext.middleware)
52
+ // All code from this point on will have access to the per-request context
34
53
  ```
35
54
 
36
- Set values based on the incoming request:
55
+ Note that some popular middlewares (such as `body-parser`, `express-jwt`) can
56
+ cause the context to be lost. To work around such problems, it is recommended
57
+ that you use any third-party middleware that does NOT require the context
58
+ BEFORE using this middleware.
59
+
60
+ ## Usage
61
+
62
+ Examples of setting values:
63
+
64
+ ```js
65
+ const httpContext = require('@dalet-oss/express-http-context')
66
+ const { nanoid } = require('nanoid') // This is just an example, nanoid is not included in this lib
37
67
 
38
- ``` js
39
- // Example authorization middleware
40
68
  app.use((req, res, next) => {
41
- userService.getUser(req.get('Authorization'), (err, result) => {
42
- if (err) {
43
- next(err);
44
- } else {
45
- httpContext.set('user', result.user)
46
- next();
47
- }
48
- });
49
- });
69
+ // Get the user ID from wherever and save it for later use...
70
+ httpContext.set('userId', userId)
71
+ // Create a request ID to be able to trace/correlate everything that happens within the same request
72
+ httpContext.set('requestId', nanoid())
73
+ })
50
74
  ```
51
75
 
52
- Get them from code that doesn't have access to the express `req` object:
76
+ Get them from anywhere in your code:
53
77
 
54
- ``` js
55
- var httpContext = require('express-http-context');
78
+ ```js
79
+ var httpContext = require('@dalet-oss/express-http-context')
56
80
 
57
- // Somewhere deep in the Todo Service
58
- function createTodoItem(title, content, callback) {
59
- var user = httpContext.get('user');
60
- db.insert({ title, content, userId: user.id }, callback);
81
+ function logError(error) {
82
+ const userId = httpContext.get('userId')
83
+ const requestId = httpContext.get('requestId')
84
+ console.error(error, { userId, requestId })
61
85
  }
62
86
  ```
63
87
 
64
- You can access cls namespace directly as (it may be useful if you want to apply some patch to it, for example https://github.com/TimBeyer/cls-bluebird):
65
- ``` js
66
- var ns = require('express-http-context').ns;
88
+ ## API
89
+
90
+ ### middleware
91
+
92
+ It is an Express.js middleware that is responsible for initializing the
93
+ independent context for each request. The `get` and `set` calls will operate on
94
+ a set of keys/values unique to those contexts.
95
+
96
+ #### Example
97
+
98
+ ```js
99
+ import { middleware } from '@dalet-oss/express-http-context'
100
+
101
+ app.use(middleware)
102
+ ```
103
+
104
+ ### set
105
+
106
+ Adds a value to the request context by key.
107
+ If the key already exists, its value will be overwritten.
108
+ No value will persist if the context has not yet been initialized.
109
+
110
+ #### Parameters
111
+
112
+ - `key` a string key to store the variable by
113
+ - `value` any value to store under the key for the later lookup.
114
+
115
+ #### Example
116
+
117
+ ```js
118
+ import { set } from '@dalet-oss/express-http-context'
119
+
120
+ set('user', { id: 'overwrittenUser', email: 'foo@bar.com' })
121
+ ```
122
+
123
+ ### get
124
+
125
+ Gets a value from the request context by key.
126
+ Will return `undefined` if the context has not yet been initialized for this
127
+ request or if a value is not found for the specified key.
128
+
129
+ #### Parameters
130
+
131
+ - `key` a string key to retrieve the stored value for
132
+
133
+ #### Example
134
+
135
+ ```js
136
+ import { get } from '@dalet-oss/express-http-context'
137
+
138
+ const user = get('user')
67
139
  ```
68
140
 
69
- ## Troubleshooting
70
- To avoid weird behavior with express:
71
- 1. Make sure you require `express-http-context` in the first row of your app. Some popular packages use async which breaks CLS.
141
+ ## License
72
142
 
73
- For users of Node 10
74
- 1. Node 10.0.x - 10.3.x are not supported. V8 version 6.6 introduced a bug that breaks async_hooks during async/await. Node 10.4.x uses V8 v6.7 in which the bug is fixed. See: https://github.com/nodejs/node/issues/20274.
143
+ MIT License. See [LICENSE](LICENSE).
75
144
 
76
- See [Issue #4](https://github.com/dalet-oss/express-http-context/issues/4) for more context. If you find any other weird behaviors, please feel free to open an issue.
77
145
 
78
146
  ## Contributors
79
147
  * Oliver Lockwood (@oliverlockwood)
80
- * Steve Konves (@skonves)
81
- * Amiram Korach (@amiram)
82
- * Yoni Rabinovitch (@yonirab)
83
- * DontRelaX (@dontrelax)
84
- * William Durand (@willdurand)
148
+ * Alberto Varela Sánchez (@artberri)
85
149
 
86
150
  Interesting in contributing? Take a look at the [Contributing Guidlines](/CONTRIBUTING.md)
package/lib/cjs/index.js CHANGED
@@ -6,7 +6,11 @@ if (!global.expressHttpContextStorage) {
6
6
  global.expressHttpContextStorage = new async_hooks_1.AsyncLocalStorage();
7
7
  }
8
8
  /**
9
- * Express.js middleware that is responsible for initializing the context for each request.
9
+ * Express.js middleware that is responsible for initializing the context for
10
+ * each request.
11
+ *
12
+ * Declared as type 'any' because otherwise Typescript consumers can get tie
13
+ * themselves in knots.
10
14
  */
11
15
  const middleware = (_req, _res, next) => {
12
16
  global.expressHttpContextStorage.run(new Map(), () => next());
@@ -14,8 +18,9 @@ const middleware = (_req, _res, next) => {
14
18
  exports.middleware = middleware;
15
19
  /**
16
20
  * Gets a value from the context by key.
17
- * Will return undefined if the context has not yet been initialized for this request
18
- * or if a value is not found for the specified key.
21
+ *
22
+ * Will return undefined if the context has not yet been initialized for this
23
+ * request, or if a value is not found for the specified key.
19
24
  */
20
25
  function get(key) {
21
26
  const store = global.expressHttpContextStorage.getStore();
@@ -24,12 +29,20 @@ function get(key) {
24
29
  exports.get = get;
25
30
  /**
26
31
  * Adds a value to the context by key.
32
+ *
27
33
  * If the key already exists, its value will be overwritten.
28
- * No value will persist if the context has not yet been initialized.
34
+ * No value will be persisted if the context has not yet been initialized.
35
+ *
36
+ * Returns the value that was set, or undefined if the context has not yet been
37
+ * initialized for this request.
29
38
  */
30
39
  function set(key, value) {
31
40
  const store = global.expressHttpContextStorage.getStore();
32
- store?.set(key, value);
41
+ if (store) {
42
+ store.set(key, value);
43
+ return value;
44
+ }
45
+ return undefined;
33
46
  }
34
47
  exports.set = set;
35
48
  exports.default = { get, middleware: exports.middleware, set };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,6CAA+C;AAS/C,IAAI,CAAC,MAAM,CAAC,yBAAyB,EAAE;IACtC,MAAM,CAAC,yBAAyB,GAAG,IAAI,+BAAiB,EAAoB,CAAA;CAC5E;AAID;;GAEG;AACI,MAAM,UAAU,GAAmB,CACzC,IAAa,EACb,IAAc,EACd,IAAkB,EACX,EAAE;IACT,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAA;AAC9D,CAAC,CAAA;AANY,QAAA,UAAU,cAMtB;AAED;;;;GAIG;AACH,SAAgB,GAAG,CAAU,GAAW;IAEvC,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAE1D,OAAO,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAA;AACvB,CAAC;AALD,kBAKC;AAED;;;;GAIG;AACH,SAAgB,GAAG,CAAU,GAAW,EAAE,KAAQ;IAEjD,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAE1D,KAAK,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;AACvB,CAAC;AALD,kBAKC;AAED,kBAAe,EAAE,GAAG,EAAE,UAAU,EAAV,kBAAU,EAAE,GAAG,EAAE,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,6CAAgD;AAUhD,IAAI,CAAC,MAAM,CAAC,yBAAyB,EAAE;IACtC,MAAM,CAAC,yBAAyB,GAAG,IAAI,+BAAiB,EAAoB,CAAC;CAC7E;AAGD;;;;;;GAMG;AACI,MAAM,UAAU,GAAQ,CAC9B,IAAa,EACb,IAAc,EACd,IAAkB,EACX,EAAE;IACT,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AAC/D,CAAC,CAAA;AANY,QAAA,UAAU,cAMtB;AAGD;;;;;GAKG;AACH,SAAgB,GAAG,CAAU,GAAW;IAEvC,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAE1D,OAAO,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;AACxB,CAAC;AALD,kBAKC;AAGD;;;;;;;;GAQG;AACH,SAAgB,GAAG,CAAU,GAAW,EAAE,KAAQ;IAEjD,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAEvD,IAAI,KAAK,EAAE;QACP,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,KAAK,CAAC;KAChB;IAED,OAAO,SAAS,CAAC;AACrB,CAAC;AAVD,kBAUC;AAGD,kBAAe,EAAE,GAAG,EAAE,UAAU,EAAV,kBAAU,EAAE,GAAG,EAAE,CAAA"}
package/lib/esm/index.js CHANGED
@@ -3,15 +3,20 @@ if (!global.expressHttpContextStorage) {
3
3
  global.expressHttpContextStorage = new AsyncLocalStorage();
4
4
  }
5
5
  /**
6
- * Express.js middleware that is responsible for initializing the context for each request.
6
+ * Express.js middleware that is responsible for initializing the context for
7
+ * each request.
8
+ *
9
+ * Declared as type 'any' because otherwise Typescript consumers can get tie
10
+ * themselves in knots.
7
11
  */
8
12
  export const middleware = (_req, _res, next) => {
9
13
  global.expressHttpContextStorage.run(new Map(), () => next());
10
14
  };
11
15
  /**
12
16
  * Gets a value from the context by key.
13
- * Will return undefined if the context has not yet been initialized for this request
14
- * or if a value is not found for the specified key.
17
+ *
18
+ * Will return undefined if the context has not yet been initialized for this
19
+ * request, or if a value is not found for the specified key.
15
20
  */
16
21
  export function get(key) {
17
22
  const store = global.expressHttpContextStorage.getStore();
@@ -19,12 +24,20 @@ export function get(key) {
19
24
  }
20
25
  /**
21
26
  * Adds a value to the context by key.
27
+ *
22
28
  * If the key already exists, its value will be overwritten.
23
- * No value will persist if the context has not yet been initialized.
29
+ * No value will be persisted if the context has not yet been initialized.
30
+ *
31
+ * Returns the value that was set, or undefined if the context has not yet been
32
+ * initialized for this request.
24
33
  */
25
34
  export function set(key, value) {
26
35
  const store = global.expressHttpContextStorage.getStore();
27
- store?.set(key, value);
36
+ if (store) {
37
+ store.set(key, value);
38
+ return value;
39
+ }
40
+ return undefined;
28
41
  }
29
42
  export default { get, middleware, set };
30
43
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAS/C,IAAI,CAAC,MAAM,CAAC,yBAAyB,EAAE;IACtC,MAAM,CAAC,yBAAyB,GAAG,IAAI,iBAAiB,EAAoB,CAAA;CAC5E;AAID;;GAEG;AACH,MAAM,CAAC,MAAM,UAAU,GAAmB,CACzC,IAAa,EACb,IAAc,EACd,IAAkB,EACX,EAAE;IACT,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAA;AAC9D,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,UAAU,GAAG,CAAU,GAAW;IAEvC,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAE1D,OAAO,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAA;AACvB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,GAAG,CAAU,GAAW,EAAE,KAAQ;IAEjD,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAE1D,KAAK,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;AACvB,CAAC;AAED,eAAe,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUhD,IAAI,CAAC,MAAM,CAAC,yBAAyB,EAAE;IACtC,MAAM,CAAC,yBAAyB,GAAG,IAAI,iBAAiB,EAAoB,CAAC;CAC7E;AAGD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,UAAU,GAAQ,CAC9B,IAAa,EACb,IAAc,EACd,IAAkB,EACX,EAAE;IACT,MAAM,CAAC,yBAAyB,CAAC,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;AAC/D,CAAC,CAAA;AAGD;;;;;GAKG;AACH,MAAM,UAAU,GAAG,CAAU,GAAW;IAEvC,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAE1D,OAAO,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;AACxB,CAAC;AAGD;;;;;;;;GAQG;AACH,MAAM,UAAU,GAAG,CAAU,GAAW,EAAE,KAAQ;IAEjD,MAAM,KAAK,GAAG,MAAM,CAAC,yBAAyB,CAAC,QAAQ,EAAE,CAAC;IAEvD,IAAI,KAAK,EAAE;QACP,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,OAAO,KAAK,CAAC;KAChB;IAED,OAAO,SAAS,CAAC;AACrB,CAAC;AAGD,eAAe,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,CAAA"}
@@ -1,29 +1,36 @@
1
1
  /// <reference types="node" />
2
- /// <reference types="qs" />
3
2
  import { AsyncLocalStorage } from 'async_hooks';
4
- import type { RequestHandler } from 'express';
5
3
  declare global {
6
4
  var expressHttpContextStorage: AsyncLocalStorage<Map<string, any>>;
7
5
  }
8
6
  /**
9
- * Express.js middleware that is responsible for initializing the context for each request.
7
+ * Express.js middleware that is responsible for initializing the context for
8
+ * each request.
9
+ *
10
+ * Declared as type 'any' because otherwise Typescript consumers can get tie
11
+ * themselves in knots.
10
12
  */
11
- export declare const middleware: RequestHandler;
13
+ export declare const middleware: any;
12
14
  /**
13
15
  * Gets a value from the context by key.
14
- * Will return undefined if the context has not yet been initialized for this request
15
- * or if a value is not found for the specified key.
16
+ *
17
+ * Will return undefined if the context has not yet been initialized for this
18
+ * request, or if a value is not found for the specified key.
16
19
  */
17
20
  export declare function get<T = any>(key: string): T | undefined;
18
21
  /**
19
22
  * Adds a value to the context by key.
23
+ *
20
24
  * If the key already exists, its value will be overwritten.
21
- * No value will persist if the context has not yet been initialized.
25
+ * No value will be persisted if the context has not yet been initialized.
26
+ *
27
+ * Returns the value that was set, or undefined if the context has not yet been
28
+ * initialized for this request.
22
29
  */
23
- export declare function set<T = any>(key: string, value: T): void;
30
+ export declare function set<T = any>(key: string, value: T): T | undefined;
24
31
  declare const _default: {
25
32
  get: typeof get;
26
- middleware: RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
33
+ middleware: any;
27
34
  set: typeof set;
28
35
  };
29
36
  export default _default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalet-oss/express-http-context",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "Modern request-scoped storage support for Express.js based on Asynchronous Local Storage.",
5
5
  "author": {
6
6
  "name": "Dalet OSS",
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { AsyncLocalStorage } from 'async_hooks'
2
- import type { NextFunction, RequestHandler, Request, Response } from 'express'
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import type { NextFunction, Request, Response } from 'express';
3
+
3
4
 
4
5
  declare global {
5
6
  // eslint-disable-next-line no-var
@@ -8,44 +9,60 @@ declare global {
8
9
 
9
10
 
10
11
  if (!global.expressHttpContextStorage) {
11
- global.expressHttpContextStorage = new AsyncLocalStorage<Map<string, any>>()
12
+ global.expressHttpContextStorage = new AsyncLocalStorage<Map<string, any>>();
12
13
  }
13
14
 
14
15
 
15
-
16
16
  /**
17
- * Express.js middleware that is responsible for initializing the context for each request.
17
+ * Express.js middleware that is responsible for initializing the context for
18
+ * each request.
19
+ *
20
+ * Declared as type 'any' because otherwise Typescript consumers can get tie
21
+ * themselves in knots.
18
22
  */
19
- export const middleware: RequestHandler = (
23
+ export const middleware: any = (
20
24
  _req: Request,
21
25
  _res: Response,
22
26
  next: NextFunction
23
27
  ): void => {
24
- global.expressHttpContextStorage.run(new Map(), () => next())
28
+ global.expressHttpContextStorage.run(new Map(), () => next());
25
29
  }
26
30
 
31
+
27
32
  /**
28
33
  * Gets a value from the context by key.
29
- * Will return undefined if the context has not yet been initialized for this request
30
- * or if a value is not found for the specified key.
34
+ *
35
+ * Will return undefined if the context has not yet been initialized for this
36
+ * request, or if a value is not found for the specified key.
31
37
  */
32
38
  export function get<T = any>(key: string): T | undefined {
33
39
 
34
40
  const store = global.expressHttpContextStorage.getStore();
35
41
 
36
- return store?.get(key)
42
+ return store?.get(key);
37
43
  }
38
44
 
45
+
39
46
  /**
40
47
  * Adds a value to the context by key.
48
+ *
41
49
  * If the key already exists, its value will be overwritten.
42
- * No value will persist if the context has not yet been initialized.
50
+ * No value will be persisted if the context has not yet been initialized.
51
+ *
52
+ * Returns the value that was set, or undefined if the context has not yet been
53
+ * initialized for this request.
43
54
  */
44
- export function set<T = any>(key: string, value: T): void {
55
+ export function set<T = any>(key: string, value: T): T | undefined {
45
56
 
46
57
  const store = global.expressHttpContextStorage.getStore();
47
58
 
48
- store?.set(key, value)
59
+ if (store) {
60
+ store.set(key, value);
61
+ return value;
62
+ }
63
+
64
+ return undefined;
49
65
  }
50
66
 
67
+
51
68
  export default { get, middleware, set }