New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

asynchronous-local-storage

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

asynchronous-local-storage - npm Package Compare versions

Comparing version 1.0.1 to 1.0.2

4

dist/index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.als = void 0;
const { isAlsSupported } = require('./lib/nodeVersionUtils');
exports.als = isAlsSupported()
const { getNodeVersion, isAlsSupported, nodeVersionString } = require('./lib/nodeVersionUtils');
exports.als = isAlsSupported(getNodeVersion(nodeVersionString))
? require('./lib/als').als

@@ -7,0 +7,0 @@ : require('./lib/cls-fallback').cls;

@@ -1,1 +0,9 @@

export declare function isAlsSupported(): boolean;
export declare const nodeVersionString: string;
declare type NodeVersion = {
majorVersion: number;
minorVersion: number;
patchVersion: number;
};
export declare function getNodeVersion(nodeVersionString: string): NodeVersion;
export declare function isAlsSupported(nodeVersion: NodeVersion): boolean;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isAlsSupported = void 0;
const nodeVersion = process.versions.node;
function getNodeVersion() {
const [nodeMajor, nodeMinor, nodePatch] = nodeVersion.split('.');
exports.isAlsSupported = exports.getNodeVersion = exports.nodeVersionString = void 0;
exports.nodeVersionString = process.versions.node;
function getNodeVersion(nodeVersionString) {
const [nodeMajor, nodeMinor, nodePatch] = nodeVersionString.split('.');
return {

@@ -13,4 +13,5 @@ majorVersion: Number.parseInt(nodeMajor),

}
function isAlsSupported() {
const { majorVersion, minorVersion } = getNodeVersion();
exports.getNodeVersion = getNodeVersion;
function isAlsSupported(nodeVersion) {
const { majorVersion, minorVersion } = nodeVersion;
if (majorVersion > 13) {

@@ -17,0 +18,0 @@ return true;

{
"name": "asynchronous-local-storage",
"version": "1.0.1",
"version": "1.0.2",
"license": "MIT",
"description": "Asynchronous local storage implementation based on Node.js ALS with fallback to cls-hooked for older Node.js versions",
"maintainers": [

@@ -17,4 +18,2 @@ {

"test:coverage": "jest --config=jest.config.json --coverage",
"test:ci": "npm run lint && npm run test:coverage",
"test:ci:legacy": "npm run test:coverage",
"lint": "eslint --format codeframe \"lib/**/*.ts\" \"test/**/*.ts\"",

@@ -28,25 +27,18 @@ "prettier": "prettier --write \"{lib,test}/**/*.{js,ts}\" index.ts",

"devDependencies": {
"@types/cls-hooked": "^4.3.0",
"@types/cls-hooked": "^4.3.1",
"@types/jest": "^24.9.1",
"@types/node": "^14.0.6",
"@typescript-eslint/eslint-plugin": "^3.0.2",
"@typescript-eslint/parser": "^3.0.2",
"eslint": "^7.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.3",
"jest": "^24.9.0",
"prettier": "^2.0.5",
"@types/node": "^14.14.20",
"@typescript-eslint/eslint-plugin": "^4.13.0",
"@typescript-eslint/parser": "^4.13.0",
"eslint": "^7.17.0",
"eslint-config-prettier": "^7.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "24.9.0",
"prettier": "^2.2.1",
"stack-utils": "1.0.4",
"ts-jest": "^24.3.0",
"typescript": "3.9.3"
"typescript": "4.1.3"
},
"jest": {
"collectCoverage": true,
"coverageThreshold": {
"global": {
"statements": 85,
"branches": 75,
"functions": 90,
"lines": 85
}
}
"engines": {
"node": ">=6"
},

@@ -53,0 +45,0 @@ "homepage": "https://github.com/kibertoad/asynchronous-local-storage",

# asynchronous-local-storage
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Linux Build][circleci-image]][circleci-url]
[![Coverage Status](https://coveralls.io/repos/kibertoad/asynchronous-local-storage/badge.svg?branch=master)](https://coveralls.io/r/kibertoad/asynchronous-local-storage?branch=master)
Asynchronous local storage implementation based on Node.js ALS with fallback to cls-hooked for older Node.js versions.

@@ -7,4 +12,3 @@

[![NPM Version][npm-image]][npm-url]
[![Linux Build][circleci-image]][circleci-url]
If you are planning to use it with [fastify](https://github.com/fastify/fastify), it is recommended to use [fastify-request-context](https://github.com/fastify/fastify-request-context) plugin instead which seamlessly integrates `asynchronous-local-storage` with the fastify request lifecycle.

@@ -17,2 +21,186 @@ ## Install

## Basic usage
### Fastify
```js
const { als } = require('asynchronous-local-storage')
const fastify = require('fastify')({ logger: true })
const asyncResourceSymbol = Symbol('asyncResource')
fastify.addHook('onRequest', (req, reply, done) => {
als.runWith(() => {
const asyncResource = new AsyncResource('my-als-context')
req[asyncResourceSymbol] = asyncResource
asyncResource.runInAsyncScope(done, req.raw)
}, { user: { id: 'defaultUser' } })
});
fastify.addHook('preValidation', (req, res, done) => {
const asyncResource = req[asyncResourceSymbol]
asyncResource.runInAsyncScope(done, req.raw)
})
fastify.addHook('preHandler', (req, reply, done) => {
// overrides default user value
als.set('user', { id: 'customUser' });
done();
});
// Declare a route
fastify.get('/', async (request, reply) => {
return {
user: als.get('user')
}
});
// Run the server!
const start = async () => {
try {
await fastify.listen(3000);
fastify.log.info(`server listening on ${fastify.server.address().port}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
}
start();
```
### Express
```js
const { als } = require('asynchronous-local-storage')
const express = require('express')
const app = express()
const port = 3000
app.use((req, res, next) => {
als.runWith(() => {
next();
}, { user: { id: 'defaultUser' } }); // sets default values
});
app.use((req, res, next) => {
// overrides default user value
als.set('user', { id: 'customUser' });
next();
});
app.get('/', (req, res) => res.send({ user: als.get('user') }))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
```
# API
### runWith
Start an asynchronous local storage context. Once this method is called, a new context is created, for which
`get` and `set` calls will operate on a set of entities, unique to this context.
#### Parameters
- `callback` - function that will be executed first within the newly created context
- `[defaults]` - an optional record, containing default values for the context
#### Examples
```javascript
const als = require('asynchronous-local-storage');
function firstCallInScope() {
// override user
als.set('user', { id: 'overwrittenUser'});
}
function secondCallInScope() {
// will print the user set in firstCallInScope
console.log(als.get('user'));
}
als.runWith(() => {
firstCallInScope();
secondCallInScope();
}, { user: { id: 'someUser' } });
```
### set
Sets a variable for a given key within running context (started by `runWith`).
If this is called outside of a running context, it will not store the value.
#### Parameters
- `key` a string key to store the variable by
- `value` any value to store under the key for the later lookup.
#### Examples
```javascript
const als = require('asynchronous-local-storage');
function callInScope() {
// override user
als.set('user', { id: 'overwrittenUser'});
}
als.runWith({ user: { id: 'someUser' } }, () => {
callInScope();
});
```
```javascript
const als = require('asynchronous-local-storage');
function callOutOfScope() {
// this never gets set
als.set('user', { id: 'overwrittenUser'});
}
// calling this won't store the variable under the key
callOutOfScope();
```
### get
Gets a variable previously set within a running context (started by `runWith`).
If this is called outside of a running context, it will not retrieve the value.
#### Parameters
- `key` a string key to retrieve the stored value for
#### Examples
```javascript
const als = require('asynchronous-local-storage');
function callInScope() {
// prints default user
console.log(als.get('user'));
}
als.runWith(() => {
callInScope();
}, { user: { id: 'someUser' } });
```
```javascript
const als = require('asynchronous-local-storage');
function callInScope() {
// prints default user
console.log(als.get('user'));
}
als.runWith(() => {
callInScope();
}, { user: { id: 'someUser' } });
// calling this will return undefined
callInScope();
```
[npm-image]: https://img.shields.io/npm/v/asynchronous-local-storage.svg

@@ -19,0 +207,0 @@ [npm-url]: https://npmjs.org/package/asynchronous-local-storage

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc