├── .gitignore ├── src ├── index.js └── Contexty.js ├── .eslintrc.yaml ├── rollup.config.js ├── package.json ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /dist/ 2 | /node_modules/ 3 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | export { default as Contexty } from './Contexty.js' 2 | -------------------------------------------------------------------------------- /.eslintrc.yaml: -------------------------------------------------------------------------------- 1 | env: 2 | es6: true 3 | node: true 4 | extends: 'eslint:recommended' 5 | parserOptions: 6 | ecmaVersion: 2017 7 | sourceType: module 8 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | entry: './src/index.js', 3 | external: ['async_hooks'], 4 | interop: false, 5 | sourceMap: true, 6 | targets: [ 7 | { dest: './dist/index.cjs.js', format: 'cjs' }, 8 | { dest: './dist/index.es.js', format: 'es' }, 9 | ], 10 | } 11 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "contexty", 3 | "version": "1.0.0", 4 | "description": "Asynchronous \"thread-local storage\" for Node.js, using async_hooks", 5 | "main": "./dist/index.cjs.js", 6 | "module": "./dist/index.es.js", 7 | "files": [ 8 | "dist" 9 | ], 10 | "scripts": { 11 | "build": "rollup -c", 12 | "lint": "eslint src rollup.config.js", 13 | "format": "prettier --write --use-tabs --no-semi --single-quote --trailing-comma es5 \"src/**/*.js\" \"*.js\"" 14 | }, 15 | "devDependencies": { 16 | "eslint": "^4.2.0", 17 | "prettier": "^1.5.3", 18 | "rollup": "^0.45.2" 19 | }, 20 | "engines": { 21 | "node": ">=8.2.0" 22 | }, 23 | "repository": { 24 | "type": "git", 25 | "url": "https://github.com/Conduitry/contexty.git" 26 | }, 27 | "author": "Conduitry", 28 | "license": "MIT", 29 | "bugs": { 30 | "url": "https://github.com/Conduitry/contexty/issues" 31 | }, 32 | "homepage": "https://contexty.unwieldy.org" 33 | } 34 | -------------------------------------------------------------------------------- /src/Contexty.js: -------------------------------------------------------------------------------- 1 | import { createHook, executionAsyncId } from 'async_hooks' 2 | 3 | let contexties = new Map() 4 | 5 | export default class Contexty { 6 | constructor() { 7 | if (contexties.size === 0) { 8 | enableHook() 9 | } 10 | contexties.set(this, new Map()) 11 | } 12 | create() { 13 | let asyncId = executionAsyncId() 14 | let contexts = contexties.get(this) 15 | let context = Object.create(contexts.get(asyncId) || null) 16 | contexts.set(asyncId, context) 17 | return context 18 | } 19 | get context() { 20 | return contexties.get(this).get(executionAsyncId()) 21 | } 22 | } 23 | 24 | function enableHook() { 25 | createHook({ 26 | init(asyncId, type, triggerAsyncId) { 27 | for (let contexts of contexties.values()) { 28 | contexts.set(asyncId, contexts.get(triggerAsyncId)) 29 | } 30 | }, 31 | destroy(asyncId) { 32 | for (let contexts of contexties.values()) { 33 | contexts.delete(asyncId) 34 | } 35 | }, 36 | }).enable() 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Conduitry 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Contexty 2 | 3 | [![npm version](https://img.shields.io/npm/v/contexty.svg?style=flat-square)](https://www.npmjs.com/package/contexty) 4 | 5 | **Contexty** is a very simple implementation of a "thread-local storage"-esque concept for Node.js, based on asynchronous resources and `async_hooks`. 6 | 7 | ## Motivation 8 | 9 | At the beginning of handling an HTTP request, you can create a new context. Elsewhere in your code, you can retrieve the current context object and get/set values on it. The context is preserved for the duration of that HTTP request, but is kept separate for different HTTP requests. This all happens without you having to pass the current context object around. 10 | 11 | ## Requirements 12 | 13 | - [Node.js](https://nodejs.org/) 8.2+ 14 | 15 | ## Usage 16 | 17 | Create an instance of `Contexty` to create a "context space" in which you want to share contexts. You should use the same `Contexty` anywhere you want to have access to the same context. In many applications, you will only need a single `Contexty` instance, which should be created *outside* the code is called asynchronously for each request/whatever. 18 | 19 | `let contexty = new Contexty()` 20 | 21 | When you want to create a new context, call `contexty.create()`. This returns a new context (an object with `null` prototype). Store whatever you want on here. Later in the same or in a descendent asynchronous call, the `contexty.context` getter will return that same context object. 22 | 23 | Calling `contexty.create()` when there is already an asynchronous context will create a new context with the old one as its prototype, so you have access to all the parent values, but new values you add to the context will not affect the parent context. 24 | 25 | ## API 26 | 27 | ### `new Contexty()` 28 | 29 | Creates a new object to manage asynchronous contexts for a particular purpose. 30 | 31 | ### `Contexty#create()` 32 | 33 | Creates and returns a new context. If a context already exists, the new context will be a child context. You can access values stored on the parent context, and any changes will no longer be accessible once you are out of this asynchronous call tree. 34 | 35 | ### `Contexty#context` 36 | 37 | The context created by the appropriate ancestor `Contexty#create`. 38 | 39 | ## Example 40 | 41 | ```javascript 42 | let { Contexty } = require('contexty') 43 | let contexty = new Contexty() 44 | 45 | let EventEmitter = require('events') 46 | let eventEmitter = new EventEmitter() 47 | eventEmitter.on('foo', () => console.log('On event: ' + contexty.context.foo)) 48 | 49 | let counter = 0 50 | 51 | async function test() { 52 | contexty.create().foo = ++counter 53 | console.log('Immediately: ' + contexty.context.foo) 54 | await sleep(1000) 55 | console.log('After await: ' + contexty.context.foo) 56 | sleep(1000).then(() => { 57 | console.log('After .then()ed promise: ' + contexty.context.foo) 58 | }) 59 | setTimeout(test2, 2000) 60 | await sleep(3000) 61 | console.log('Back in original context: ' + contexty.context.foo) 62 | await sleep(1000) 63 | eventEmitter.emit('foo') 64 | } 65 | 66 | function test2() { 67 | console.log('After timeout: ' + contexty.context.foo) 68 | contexty.create() 69 | console.log('In child context: ' + contexty.context.foo) 70 | contexty.context.foo = 'x' 71 | console.log('With overridden value: ' + contexty.context.foo) 72 | } 73 | 74 | for (let i = 0; i < 3; i++) { 75 | test() 76 | } 77 | 78 | function sleep(ms) { 79 | return new Promise(res => setTimeout(res, ms)) 80 | } 81 | ``` 82 | 83 | Output: 84 | 85 | ``` 86 | Immediately: 1 87 | Immediately: 2 88 | Immediately: 3 89 | After await: 1 90 | After await: 2 91 | After await: 3 92 | After .then()ed promise: 1 93 | After .then()ed promise: 2 94 | After .then()ed promise: 3 95 | After timeout: 1 96 | In child context: 1 97 | With overridden value: x 98 | After timeout: 2 99 | In child context: 2 100 | With overridden value: x 101 | After timeout: 3 102 | In child context: 3 103 | With overridden value: x 104 | Back in original context: 1 105 | Back in original context: 2 106 | Back in original context: 3 107 | On event: 1 108 | On event: 2 109 | On event: 3 110 | ``` 111 | 112 | ## License 113 | 114 | Copyright (c) 2017 Conduitry 115 | 116 | - [MIT](https://github.com/Conduitry/contexty/blob/master/LICENSE) 117 | --------------------------------------------------------------------------------