Giter Site home page Giter Site logo

cls-adapter's Introduction

@emartech/cls-adapter

A wrapper around the Continuation Local Storage library cls-hooked. Makes storing and retrieving of context dependent information easier. It acts as a thread aware storage.

When a value is set on the storage with a given key, that value will be available inside functions calls from the parent function.

Installation

npm install @emartech/cls-adapter

Usage

const Koa = require('koa');
const ClsAdapter = require('@emartech/cls-adapter');

const logWithStorage = (message) => {
  console.log(Object.assign({ message }, ClsAdapter.getContextStorage()));
};
const calculationResult = () => {
  logWithStorage(100);
};

const app = new Koa();
app.use(ClsAdapter.getKoaMiddleware());

app.use(async (ctx) => {
  ClsAdapter.setOnContext('customer_id', 1000);

  logWithStorage('works');
  // { message: 'works', request_id: 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a' }
  
  calculationResult();
  // { message: 100, request_id: 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a' }

  ctx.body = 'It works';
});

app.listen(3000);

API

ClsAdapter.getKoaMiddleware()

Returns a middleware function compatible with Koa that stores (or generates if missing) the request identifier from the header (X-Request-Id) and sets it on the storage as request_id.

const app = new Koa();
app.use(ClsAdapter.getKoaMiddleware());

app.use(async () => {
  ClsAdapter.getContextStorage();
  // { request_id: 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a' }
});

ClsAdapter.getExpressMiddleware()

Returns a middleware function compatible with Express that stores (or generates if missing) the request identifier from the header (X-Request-Id) and sets it on the storage as request_id.

const app = express();
app.use(ClsAdapter.getExpressMiddleware());

app.use(() => {
  ClsAdapter.getContextStorage();
  // { request_id: 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a' }
});

ClsAdapter.getContextStorage()

Returns the all the values set on the storage.

ClsAdapter.setOnContext(key, value)

Sets a key with a given value on the storage.

ClsAdapter.setOnContext('customer_id', 1);
ClsAdapter.setOnContext('application.customer.id', 11);

ClsAdapter.getContextStorage();
// { customer_id: 1, application: { customer: { id: 11 } } }

ClsAdapter.getRequestId()

Returns the the request identifier set on the storage. The identifiers key is request_id.

ClsAdapter.setOnContext('request_id', 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a');
ClsAdapter.getRequestId();
// 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a'

ClsAdapter.addContextStorageToInput()

Returns a function that extends the given object with the current storage.

ClsAdapter.setOnContext('customer_id', 1);

ClsAdapter.addContextStorageToInput()({ debug: true });
// { debug: true, customer_id: 1 }

ClsAdapter.addRequestIdToInput()

Returns a function that extends the given object with the request identifier set on the current storage.

ClsAdapter.setOnContext('request_id', 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a');

ClsAdapter.addRequestIdToInput()({ debug: true });
// { debug: true, request_id: 'd5caaa0e-b04e-4d94-bc88-3ed3b62dc94a' }

cls-adapter's People

Contributors

akapa avatar edevil avatar halaz-lazlo avatar sonicoder86 avatar szeist avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cls-adapter's Issues

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Compatibility with koa-logger

koa-logger is a Koa middleware that calls a user supplied callback at the start and end of requests, so as to print information such as latency, status code, etc.

When the callback is called at the beginning of the request we have access to the cls context. However, when we are called at the end this context is not there. This is because the callback is called in the context of a "finished" or "close" event on ctx.res. Relevant code.

I've made it work by altering the module code:

const namespace = cls.createNamespace();
res.once('finish', namespace.bind(onfinish));

Is there any way to do just from my app side?

Typescript declarations

I'm looking to use this adapter in one of my typescript projects.

Currently the library does nto have type declarations, here, or in the global DefinitelyTyped project.

I'm willing to put in the work to create typings for this project, and the best thing to do would be to include type declaration files in the repo itself.

If this is something you are open to i can look into generating the types and can raise a pull request with them. Alternatively i can submit them to the DefinitelyTyped project extnernaly.

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.