@dalet-oss/express-http-context 1.0.0-DEV

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Steve Konves
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,86 @@
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)
6
+
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
+
13
+ ## How to use it
14
+
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`)
17
+
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.
20
+
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.
24
+
25
+ ``` js
26
+ var express = require('express');
27
+ var httpContext = require('express-http-context');
28
+
29
+ var app = express();
30
+ // Use any third party middleware that does not need access to the context here, e.g.
31
+ // app.use(some3rdParty.middleware);
32
+ app.use(httpContext.middleware);
33
+ // all code from here on has access to the same context for each request
34
+ ```
35
+
36
+ Set values based on the incoming request:
37
+
38
+ ``` js
39
+ // Example authorization middleware
40
+ 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
+ });
50
+ ```
51
+
52
+ Get them from code that doesn't have access to the express `req` object:
53
+
54
+ ``` js
55
+ var httpContext = require('express-http-context');
56
+
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);
61
+ }
62
+ ```
63
+
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;
67
+ ```
68
+
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.
72
+
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.
75
+
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
+
78
+ ## Contributors
79
+ * Oliver Lockwood (@oliverlockwood)
80
+ * Steve Konves (@skonves)
81
+ * Amiram Korach (@amiram)
82
+ * Yoni Rabinovitch (@yonirab)
83
+ * DontRelaX (@dontrelax)
84
+ * William Durand (@willdurand)
85
+
86
+ Interesting in contributing? Take a look at the [Contributing Guidlines](/CONTRIBUTING.md)
package/browser.js ADDED
@@ -0,0 +1,12 @@
1
+ module.exports = {
2
+ middleware: function (req, res, next) {
3
+ throw new Error('`middleware` cannot be called from the browser code.');
4
+ },
5
+ get: function () {
6
+ return null;
7
+ },
8
+ set: function (key, value) {
9
+ // noop
10
+ },
11
+ ns: null,
12
+ };
package/index.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { Request, Response, NextFunction } from "express";
2
+ import { Namespace } from 'cls-hooked';
3
+
4
+ /** Express.js middleware that is responsible for initializing the context for each request. */
5
+ export declare function middleware(
6
+ req: Request,
7
+ res: Response,
8
+ next: NextFunction
9
+ ): void;
10
+
11
+ /**
12
+ * Gets a value from the context by key. Will return undefined if the context has not yet been initialized for this request or if a value is not found for the specified key.
13
+ */
14
+ export declare function get(key: string): any;
15
+
16
+ /**
17
+ * Adds a value to the context by key. If the key already exists, its value will be overwritten. No value will persist if the context has not yet been initialized.
18
+ */
19
+ export declare function set(key: string, value: any): void;
20
+
21
+ /**
22
+ * Gets the underlying continuation namespace.
23
+ */
24
+ export declare const ns: Namespace;
package/index.js ADDED
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ const cls = require('cls-hooked');
4
+
5
+ const nsid = 'a6a29a6f-6747-4b5f-b99f-07ee96e32f88';
6
+ const ns = cls.createNamespace(nsid);
7
+
8
+ /** Express.js middleware that is responsible for initializing the context for each request. */
9
+ function middleware(req, res, next) {
10
+ ns.run(() => next());
11
+ }
12
+
13
+ /**
14
+ * Gets a value from the context by key. Will return undefined if the context has not yet been initialized for this request or if a value is not found for the specified key.
15
+ * @param {string} key
16
+ */
17
+ function get(key) {
18
+ if (ns && ns.active) {
19
+ return ns.get(key);
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Adds a value to the context by key. If the key already exists, its value will be overwritten. No value will persist if the context has not yet been initialized.
25
+ * @param {string} key
26
+ * @param {*} value
27
+ */
28
+ function set(key, value) {
29
+ if (ns && ns.active) {
30
+ return ns.set(key, value);
31
+ }
32
+ }
33
+
34
+ module.exports = {
35
+ middleware,
36
+ get: get,
37
+ set: set,
38
+ ns: ns
39
+ };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@dalet-oss/express-http-context",
3
+ "version": "1.0.0-DEV",
4
+ "description": "Get and set request-scoped context anywhere",
5
+ "main": "index.js",
6
+ "browser": "browser.js",
7
+ "types": "./index.d.ts",
8
+ "engines": {
9
+ "node": ">=16.0.0"
10
+ },
11
+ "scripts": {
12
+ "test": "node --unhandled-rejections=strict ./node_modules/.bin/mocha --config test/.mocharc.json",
13
+ "cover": "nyc --reporter lcov --reporter text-summary _mocha --config test/.mocharc.json",
14
+ "coveralls": "npm run cover -- --report lcovonly && cat ./coverage/lcov.info | coveralls"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/dalet-oss/express-http-context.git"
19
+ },
20
+ "keywords": [
21
+ "express",
22
+ "http",
23
+ "request",
24
+ "context"
25
+ ],
26
+ "author": "Oliver Lockwood",
27
+ "contributors": [
28
+ "Oliver Lockwood (@oliverlockwood)",
29
+ "Steve Konves (@skonves)",
30
+ "Amiram Korach (@amiram)",
31
+ "Yoni Rabinovitch (@yonirab)",
32
+ "DontRelaX (@dontrelax)",
33
+ "William Durand (@willdurand)"
34
+ ],
35
+ "license": "MIT",
36
+ "bugs": {
37
+ "url": "https://github.com/dalet-oss/express-http-context/issues"
38
+ },
39
+ "homepage": "https://github.com/dalet-oss/express-http-context#readme",
40
+ "directories": {
41
+ "test": "test"
42
+ },
43
+ "dependencies": {
44
+ "@types/cls-hooked": "^4.2.1",
45
+ "@types/express": "^4.17.17",
46
+ "cls-hooked": "^4.2.2"
47
+ },
48
+ "devDependencies": {
49
+ "chai": "^4.3.7",
50
+ "coveralls": "^3.1.1",
51
+ "express": "^4.18.2",
52
+ "nyc": "^15.1.0",
53
+ "mocha": "^10.2.0",
54
+ "mocha-lcov-reporter": "^1.3.0",
55
+ "supertest": "^6.3.3"
56
+ }
57
+ }