Giter Site home page Giter Site logo

maxgfr / node-simple-context Goto Github PK

View Code? Open in Web Editor NEW
1.0 3.0 1.0 1.69 MB

A minimalist context for node, inspired by React Context API

Home Page: https://www.npmjs.com/package/node-simple-context

License: MIT License

JavaScript 2.94% TypeScript 97.06%
context node-context context-api global-variables typescript async-hooks promise async-local-storage

node-simple-context's Introduction

node-simple-context

node-simple-context is an helper to create a context in node.

This library is highly inspired by nctx. You definitely should check it out! Thanks to @devthejo for his help ๐Ÿ’ช

Installation

npm install node-simple-context

Usage

Simple example

1. Create a new file my-context.ts in which you define your context.

import { createSimpleContext } from 'node-simple-context';

export const contextA = createSimpleContext();
export const contextB = createSimpleContext();

2. You now can set the context in your code wherever you want

import { contextA, contextB } from './my-context';

contextA.set('foo', 'bar');
contextB.set('foo', 'baz');

3. And, get your context value wherever you want

import { contextA, contextB } from './my-context';

console.log(contextA.get('foo')); // bar
console.log(contextB.get('foo')); // baz
console.log(contextA.get('xxx')); // undefined

// in typescript
console.log(contextA.get<string>('foo')); // bar

Complex examples

By forking your context

Thanks to AsyncLocalStorage api, you can fork your context in promise or async functions. As you can see below:

You can also pass a callback in fork method to runs a function synchronously within a context and returns its return value which uses run method from AsyncLocalStorage (cf. example)

const context = createSimpleContext();

const func = (): string => {
  const foo = context.get('foo');
  return `foo=${foo}`;
};

context.fork();
context.set('foo', 'bar');

const res = await Promise.all([
  new Promise((resolve) => {
    context.fork().set('foo', 'tata');
    setTimeout(() => {
      resolve(func());
    }, 400);
  }),
  new Promise((resolve) => {
    context.fork().set('foo', 'toto');
    setTimeout(() => {
      resolve(func());
    }, 200);
  }),
  new Promise((resolve) => {
    context.fork().set('foo', 'titi');
    setTimeout(() => {
      resolve(func());
    }, 100);
  }),
  new Promise((resolve) => {
    context.fork().set('foo', 'tutu');
    setTimeout(() => {
      resolve(func());
    }, 600);
  }),
]);

console.log(res); // ['foo=tata', 'foo=toto', 'foo=titi', 'foo=tutu']

By using multiple contexts

const contextA = createSimpleContext();
const contextB = createSimpleContext();
const contextC = createSimpleContext();
const contextD = createSimpleContext();

const func = (context: SimpleContext): string => {
  const foo = context.get('foo');
  return `foo=${foo}`;
};

const res = await Promise.all([
  new Promise((resolve) => {
    contextA.set('foo', 'tata');
    setTimeout(() => {
      resolve(func(contextA));
    }, 400);
  }),
  new Promise((resolve) => {
    contextB.set('foo', 'toto');
    setTimeout(() => {
      resolve(func(contextB));
    }, 200);
  }),
  new Promise((resolve) => {
    contextC.set('foo', 'titi');
    setTimeout(() => {
      resolve(func(contextC));
    }, 100);
  }),
  new Promise((resolve) => {
    contextD.set('foo', 'tutu');
    setTimeout(() => {
      resolve(func(contextD));
    }, 600);
  }),
]);

console.log(res); // ['foo=tata', 'foo=toto', 'foo=titi', 'foo=tutu']

By using multiple keys

const context = createSimpleContext();

const func = (key: string): string => {
  const foo = context.get(key);
  return `foo=${foo}`;
};

const res = await Promise.all([
  new Promise((resolve) => {
    context.set('foo1', 'tata');
    setTimeout(() => {
      resolve(func('foo1'));
    }, 400);
  }),
  new Promise((resolve) => {
    context.set('foo2', 'toto');
    setTimeout(() => {
      resolve(func('foo2'));
    }, 200);
  }),
  new Promise((resolve) => {
    context.set('foo3', 'titi');
    setTimeout(() => {
      resolve(func('foo3'));
    }, 100);
  }),
  new Promise((resolve) => {
    context.set('foo4', 'tutu');
    setTimeout(() => {
      resolve(func('foo4'));
    }, 600);
  }),
]);

console.log(res); // ['foo=tata', 'foo=toto', 'foo=titi', 'foo=tutu']

node-simple-context's People

Contributors

maxgfr avatar renovate-bot avatar renovate[bot] avatar semantic-release-bot avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Forkers

pranav403

node-simple-context's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v3
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
.github/workflows/lint.yml
  • actions/checkout v3
.github/workflows/publish.yml
  • actions/checkout v3
.github/workflows/test.yml
  • actions/checkout v3
npm
package.json
  • @semantic-release/commit-analyzer 10.0.4
  • @semantic-release/git 10.0.1
  • @semantic-release/github 9.2.6
  • @semantic-release/npm 10.0.6
  • @semantic-release/release-notes-generator 11.0.7
  • @swc-node/register 1.9.1
  • @swc/cli 0.3.12
  • @swc/core 1.5.7
  • @swc/jest 0.2.36
  • @types/jest 29.5.12
  • @types/node 18.19.33
  • @typescript-eslint/eslint-plugin 5.62.0
  • @typescript-eslint/parser 5.62.0
  • eslint 8.57.0
  • eslint-config-prettier 8.10.0
  • eslint-plugin-jest 27.9.0
  • jest 29.7.0
  • nodemon 3.1.1
  • prettier 3.2.5
  • rimraf 5.0.7
  • semantic-release 21.1.2
  • typescript 5.4.5

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.