Big news!Introducing Socket AI - ChatGPT-Powered Threat Analysis. Learn more
Socket
Log inDemoInstall

@travetto/context

Package Overview
Dependencies
1
Maintainers
1
Versions
227
Issues
File Explorer

Advanced tools

@travetto/context

Async-aware state management, maintaining context across asynchronous calls.

    3.1.1latest
    GitHub

Version published
Maintainers
1
Weekly downloads
1,484
increased by61.83%

Weekly downloads

Readme

Source

Async Context

Async-aware state management, maintaining context across asynchronous calls.

Install: @travetto/context

npm install @travetto/context # or yarn add @travetto/context

This module provides a wrapper around node's async_hooks to maintain context across async calls. This is generally used for retaining contextual user information at various levels of async flow.

The most common way of utilizing the context, is via the WithAsyncContext decorator. The decorator requires the class it's being used in, to have a AsyncContext member, as it is the source of the contextual information.

The decorator will load the context on invocation, and will keep the context active during the entire asynchronous call chain.

Code: Usage of context within a service

import { AsyncContext, WithAsyncContext } from '@travetto/context'; export class ContextAwareService { constructor(public context: AsyncContext) { } @WithAsyncContext() async complexOperator(name: string) { this.context.set({ name }); await this.additionalOp('extra'); await this.finalOp(); } async additionalOp(additional: string) { const { name } = this.context.get(); this.context.set({ name: `${name} ${additional}` }); } async finalOp() { const { name } = this.context.get(); // Use name return name; } }

The decorator also allows for a priming of the contextual information. This is generally useful for system generated operations that are not initiated by a user.

Code: Usage of context within a service

import { AsyncContext, WithAsyncContext } from '@travetto/context'; export class SystemInitiatedContext { constructor(public context: AsyncContext) { } @WithAsyncContext({ user: 'system', uid: 20 }) async runJob(name: string) { console.log('Running', { user: this.context.get().user, jobName: name }); } }

Keywords

FAQs

Last updated on 01 Apr 2023

Did you know?

Socket installs a Github app to automatically flag issues on every pull request and report the health of your dependencies. Find out what is inside your node modules and prevent malicious activity before you update the dependencies.

Install Socket
Socket
support@socket.devSocket SOC 2 Logo

Product

  • Package Issues
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc