https://github.com/ziv/local-storage
AsyncLocalStorage middleware
https://github.com/ziv/local-storage
Last synced: 8 months ago
JSON representation
AsyncLocalStorage middleware
- Host: GitHub
- URL: https://github.com/ziv/local-storage
- Owner: ziv
- License: mit
- Archived: true
- Created: 2021-07-08T12:04:06.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2024-11-11T05:05:00.000Z (over 1 year ago)
- Last Synced: 2025-03-04T18:25:53.601Z (about 1 year ago)
- Language: TypeScript
- Size: 580 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# local-storage
[](https://github.com/ziv/local-storage/actions/workflows/main.yml)
[](https://codecov.io/gh/ziv/local-storage)
[AsyncLocalStorage](https://nodejs.org/api/async_context.html#async_context_class_asynclocalstorage) middleware.
## Install
```shell
npm i @xpr/local-storage
```
## Usage
```typescript
import { localStorage, getStore } from '@xpr/local-storage';
const app = express();
// The middleware starts an async hooks trap.
//
// From now on, every function called after
// this middleware run, can access the [[Request]]
// and the [[Response]] of the same context using
// the [[getStore]] function.
app.use(localStorage());
app.use((req, res, next) => {
req.locals.RAND = generateRandNumber();
});
function logger(message: string) {
const store = getStore();
if (store) {
// we've been called from inside async trap
// we can use the store content
const id = store.request.locals.RAND;
console.log(id, message);
} else {
console.log(null, message);
}
}
```
---


