fix(readme): Update README.md for better clarity and examples.

This commit is contained in:
Philipp Kunz 2025-01-19 00:29:00 +01:00
parent 36d52a9e03
commit 18f63b07f7
3 changed files with 121 additions and 73 deletions

View File

@ -1,5 +1,13 @@
# Changelog
## 2025-01-19 - 2.1.3 - fix(readme)
Update README.md for better clarity and examples.
- Enhanced documentation with clearer examples of AsyncContext usage.
- Reorganized sections for improved understanding of `runScoped` and its benefits.
- Added detailed test script example in README.md.
- Clarified data isolation and deletion mechanisms within scoped functions.
## 2025-01-19 - 2.1.2 - fix(core)
Improve scope handling in async contexts.

184
readme.md
View File

@ -14,156 +14,196 @@ This will install the library and its dependencies into your local `node_modules
## Usage
The `@push.rocks/smartcontext` module provides an efficient way to enrich your logging (or any functionality) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly handy when dealing with complex or nested asynchronous operations in Node.js.
The `@push.rocks/smartcontext` module provides an efficient way to enrich your code (often for logging) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly helpful in complex or nested asynchronous operations in Node.js.
### Setting Up and Basic Usage
First, import the necessary classes:
### Basic Setup
```typescript
import { AsyncContext } from '@push.rocks/smartcontext';
```
#### Creating a Context
An `AsyncContext` manages a top-level `AsyncStore`. You can attach any data you want to that store. For example:
```typescript
const asyncContext = new AsyncContext();
// Add data to the top-level store
// The parent store is always accessible through `asyncContext.store`
asyncContext.store.add('username', 'john_doe');
console.log(asyncContext.store.get('username')); // 'john_doe'
```
### Using `runScoped`
The `runScoped` method now creates a child store *automatically* and makes that child store accessible via `asyncContext.store` **only** within the passed-in function. Once that scoped function completes, `asyncContext.store` reverts to the original (parent) store.
### `runScoped`
#### Example
When you call `asyncContext.runScoped(async () => { ... })`, the library automatically creates a **child** `AsyncStore`. Inside that scoped function, `asyncContext.store` refers to the child store. Any data you add or delete there is isolated from the parent store. However, you can still read parent data if it hasnt been overridden.
```typescript
await asyncContext.runScoped(async () => {
// While in this scope, asyncContext.store refers to the child store.
asyncContext.store.add('transactionId', 'txn_123456');
console.log(asyncContext.store.get('transactionId')); // 'txn_123456'
// Inside this callback, `asyncContext.store` is a *child* store
asyncContext.store.add('transactionId', 'txn_abc123');
console.log(asyncContext.store.get('transactionId')); // 'txn_abc123'
// Data from the parent store is also accessible in the child
// We can also see parent data like 'username'
console.log(asyncContext.store.get('username')); // 'john_doe'
});
// Outside runScoped, asyncContext.store is the parent store again
console.log(asyncContext.store.get('transactionId')); // undefined
// Outside `runScoped`, asyncContext.store reverts to the parent store
console.log(asyncContext.store.get('transactionId')); // undefined
```
1. **Child Store Access**: Within the scope, `asyncContext.store` points to a *child* store.
2. **Parent Data**: Any keys from the parent are still visible in the child (unless overridden).
3. **No Cross-Contamination**: Keys added in the child store dont persist in the parent after the scope ends.
### Isolating and Deleting Data
### Isolating Data
If you add a key within a `runScoped` block, it stays there unless you intentionally move it to the parent. Also, if you delete a key in the child, it wont remove it from the parent store:
Because each call to `runScoped` returns control to the parent store afterward, any keys added in a child scope disappear once the scope completes (unless you explicitly move them to the parent). This mechanism keeps data from leaking between scopes.
```typescript
// Parent store has some initial data
asyncContext.store.add('deletableKey', 'initialValue');
// Parent store
asyncContext.store.add('someParentKey', 'parentValue');
// Child scope
await asyncContext.runScoped(async () => {
console.log(asyncContext.store.get('deletableKey')); // 'initialValue'
asyncContext.store.delete('deletableKey'); // Delete in child
console.log(asyncContext.store.get('deletableKey')); // undefined (child only)
asyncContext.store.add('scopedKey', 'childValue');
console.log(asyncContext.store.get('scopedKey')); // 'childValue'
});
// Outside scope, parent's data is intact
console.log(asyncContext.store.get('deletableKey')); // 'initialValue'
// Outside, the child key is gone
console.log(asyncContext.store.get('scopedKey')); // undefined
```
### Multiple Scopes
You can create multiple scopes, each maintaining its own data isolation. That way, concurrent or sequential operations dont overwrite or “contaminate” each others data in the shared context.
### Deleting Data
If the child deletes a key that exists in the parent, it will only remove it from the childs view of the store. Once the scope completes, the parent store is unaffected.
```typescript
// Scope 1
asyncContext.store.add('deletableKey', 'originalValue');
await asyncContext.runScoped(async () => {
asyncContext.store.add('key1', 'value1');
console.log(asyncContext.store.get('key1')); // 'value1'
console.log(asyncContext.store.get('deletableKey')); // 'originalValue'
asyncContext.store.delete('deletableKey');
console.log(asyncContext.store.get('deletableKey')); // undefined in child
});
// Scope 2
await asyncContext.runScoped(async () => {
asyncContext.store.add('key2', 'value2');
console.log(asyncContext.store.get('key2')); // 'value2'
});
// After both scopes finish, neither key1 nor key2 is visible to the parent
console.log(asyncContext.store.get('key1')); // undefined
console.log(asyncContext.store.get('key2')); // undefined
console.log(asyncContext.store.get('deletableKey')); // 'originalValue' remains in parent
```
### Deeper Nesting
If you nest `runScoped` calls, each subsequent call creates another child store, which inherits from the store thats currently active. This allows you to build deeper context layers when needed.
### Parallel or Sequential Scopes
You can call `runScoped` multiple times, whether sequentially or in parallel (with `Promise.all`). Each invocation creates its own isolated child store, preventing data collisions across asynchronous tasks.
```typescript
await asyncContext.runScoped(async () => {
asyncContext.store.add('layer1', true);
await asyncContext.runScoped(async () => {
asyncContext.store.add('layer2', true);
// This store sees data from both layer1 and layer2
console.log(asyncContext.store.get('layer1')); // true
console.log(asyncContext.store.get('layer2')); // true
});
// Only layer1 data remains in scope here; layer2 is gone
console.log(asyncContext.store.get('layer2')); // undefined
asyncContext.store.add('childKey1', 'childValue1');
console.log(asyncContext.store.get('childKey1')); // 'childValue1'
});
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
console.log(asyncContext.store.get('childKey2')); // 'childValue2'
});
// Both keys were added in separate scopes, so they won't exist in the parent
console.log(asyncContext.store.get('childKey1')); // undefined
console.log(asyncContext.store.get('childKey2')); // undefined
```
### Testing
Below is a simplified test example using [tapbundle](https://www.npmjs.com/package/@push.rocks/tapbundle). It demonstrates `runScoped()` creating isolated child stores and verifying behavior such as data inheritance and cleanup:
### Testing Example
The following is a complete test script (using [tapbundle](https://www.npmjs.com/package/@push.rocks/tapbundle)) demonstrating how child stores inherit data from the parent but remain isolated. After each scoped block, new child keys vanish, and any parent keys deleted inside the child remain intact in the parent.
```typescript
import { tap, expect } from '@push.rocks/tapbundle';
import { AsyncContext } from './logcontext.classes.asynccontext.js';
import { AsyncContext } from '../ts/logcontext.classes.asynccontext.js';
const asyncContext = new AsyncContext();
tap.test('should run scoped and see parent data', async () => {
tap.test('should run a scoped function and add data to a child store', async () => {
// Add some default data to the parent store
asyncContext.store.add('parentKey', 'parentValue');
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
// Now run a child scope, add some data, and check that parent data is still accessible
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey', 'childValue');
// Child sees its own data
expect(asyncContext.store.get('childKey')).toEqual('childValue');
// Child also sees parent data
expect(asyncContext.store.get('parentKey')).toEqual('parentValue');
});
});
tap.test('should isolate new keys within a child scope', async () => {
tap.test('should not contaminate the parent store with child-only data', async () => {
// Create a new child scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('temporaryKey', 'temporaryValue');
expect(asyncContext.store.get('temporaryKey')).toEqual('temporaryValue');
});
// Key won't leak to the parent
// After scope finishes, 'temporaryKey' won't exist in the parent
expect(asyncContext.store.get('temporaryKey')).toBeUndefined();
});
// More tests ...
tap.test('should allow adding data in multiple scopes independently', async () => {
// Add data in the first scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey1', 'childValue1');
expect(asyncContext.store.get('childKey1')).toEqual('childValue1');
});
tap.start();
// Add data in the second scope
await asyncContext.runScoped(async () => {
asyncContext.store.add('childKey2', 'childValue2');
expect(asyncContext.store.get('childKey2')).toEqual('childValue2');
});
// Neither childKey1 nor childKey2 should exist in the parent store
expect(asyncContext.store.get('childKey1')).toBeUndefined();
expect(asyncContext.store.get('childKey2')).toBeUndefined();
});
tap.test('should allow deleting data in a child store without removing it from the parent store', async () => {
// Ensure parent has some data
asyncContext.store.add('deletableKey', 'iShouldStayInParent');
await asyncContext.runScoped(async () => {
// Child sees the parent's data
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
// Delete it in the child
asyncContext.store.delete('deletableKey');
// Child no longer sees it
expect(asyncContext.store.get('deletableKey')).toBeUndefined();
});
// Parent still has it
expect(asyncContext.store.get('deletableKey')).toEqual('iShouldStayInParent');
});
tap.test('should allow multiple child scopes to share the same parent store data', async () => {
// Add a key to the parent store
asyncContext.store.add('sharedKey', 'sharedValue');
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
// First child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
// Second child scope
await asyncContext.runScoped(async () => {
expect(asyncContext.store.get('sharedKey')).toEqual('sharedValue');
});
});
export default tap.start();
```
### Conclusion
The updated `runScoped` usage makes child store management more intuitive by dynamically switching `asyncContext.store` to a child store inside the scope, then reverting back to the parent store afterwards. This design ensures:
With this updated `runScoped` design, theres no need to explicitly instantiate or manage child stores. The context automatically switches from the parent store to the child store while within the callback, then reverts back to the parent store afterwards. This structure makes it easy to:
- **Scoped Modifications**: Data added or removed in a child scope stays in that scope.
- **Parent Inheritance**: Child scopes still read the parents data.
- **Easy Syntax**: No need to pass the child store around; simply call `asyncContext.store` within `runScoped`.
- Keep each async operations state isolated
- Preserve read-access to parent context data
- Avoid overwriting or polluting other operations data
With `@push.rocks/smartcontext`, you can maintain clear boundaries between different parts of your asynchronous code. This not only enriches your logging with context but also simplifies tracking data across nested or concurrent operations.
This pattern works particularly well for logging or any scenario where you need to pass metadata through deeply nested async calls without manually juggling that data everywhere in your code.
## License and Legal Information

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartcontext',
version: '2.1.2',
version: '2.1.3',
description: 'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.'
}