How to use continuation-local-storage - 10 common examples

To help you get started, we’ve selected a few continuation-local-storage examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github logerzhu / simple-graphql / src / sequelize / __tests__ / sequelize.js View on Github external
// @flow
import Sequelize from 'sequelize'
import cls from 'continuation-local-storage'

const namespace = cls.createNamespace('my-db-namespace')
Sequelize['useCLS'](namespace)

const sequelize = new Sequelize('clinic', 'tester', 'password', {
  host: 'localhost',
  dialect: 'sqlite',

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },
  // SQLite only
  storage: ':memory:',
  logging: (str) => console.log(str),
  define: {
    underscored: true,
github motdotla / node-lambda / lib / main.js View on Github external
context.getRemainingTimeInMillis = () => {
      const currentTime = new Date()
      return timeout - (currentTime - startTime)
    }

    // The following three functions are deprecated in AWS Lambda.
    // Since it is sometimes used by other SDK,
    // it is a simple one that does not result in `not function` error
    context.succeed = (result) => console.log(JSON.stringify(result))
    context.fail = (error) => console.log(JSON.stringify(error))
    context.done = (error, results) => {
      console.log(JSON.stringify(error))
      console.log(JSON.stringify(results))
    }

    const nameSpace = createNamespace('AWSXRay')
    nameSpace.run(() => {
      nameSpace.set('segment', new AWSXRay.Segment('annotations'))
      const result = handler(event, context, callback)
      if (result != null) {
        Promise.resolve(result).then(
          resolved => {
            console.log('Result:')
            console.log(JSON.stringify(resolved))
          },
          rejected => {
            console.log('Error:')
            console.log(rejected)
          }
        )
      }
    })
github alphagov / pay-selfservice / app / controllers / dashboard / dashboard-activity-controller.js View on Github external
try {
    const { fromDateTime, toDateTime } = getTransactionDateRange(period)

    const transactionsPeriodString = `fromDate=${encodeURIComponent(datetime(fromDateTime, 'date'))}&fromTime=${encodeURIComponent(datetime(fromDateTime, 'time'))}&toDate=${encodeURIComponent(datetime(toDateTime, 'date'))}&toTime=${encodeURIComponent(datetime(toDateTime, 'time'))}`

    logger.info(`[${correlationId}] successfully logged in`)

    if (isADirectDebitAccount(gatewayAccountId)) {
      // todo implement transaction list for direct debit
      return response(req, res, 'dashboard/index', Object.assign(model, {
        activityError: true
      }))
    }

    const namespace = getNamespace(clsXrayConfig.nameSpaceName)
    const clsSegment = namespace.get(clsXrayConfig.segmentKeyName)

    AWSXRay.captureAsyncFunc('ledgerClient_getTransactionSummary', function (subsegment) {
      LedgerClient.transactionSummary(gatewayAccountId, fromDateTime, toDateTime, { correlationId: correlationId })
        .then(result => {
          subsegment.close()
          response(req, res, 'dashboard/index', Object.assign(model, {
            activity: result,
            successfulTransactionsState: 'payment-success',
            fromDateTime,
            toDateTime,
            transactionsPeriodString
          }))
        })
        .catch((error, ledgerResponse) => {
          subsegment.close(error)
github strongloop / loopback / server / current-context.js View on Github external
loopback.createContext = function(scopeName) {
    // Make the namespace globally visible via the process.context property
    process.context = process.context || {};
    var ns = process.context[scopeName];
    if (!ns) {
      ns = cls.createNamespace(scopeName);
      process.context[scopeName] = ns;
      // Set up loopback.getCurrentContext()
      loopback.getCurrentContext = function() {
        return ns && ns.active ? ns : null;
      };

      chain(juggler);
      chain(remoting);
    }
    return ns;
  };
github yurishkuro / opentracing-tutorial / nodejs / lesson04 / solution / hello-context.js View on Github external
var ns = require('continuation-local-storage').createNamespace('myNameSpace');
require('cls-bluebird')( ns );
// Promise is now patched to maintain CLS context

const assert = require('assert');
const initTracer = require('../../lib/tracing').initTracer;
const request = require('request-promise');
const { Tags, FORMAT_HTTP_HEADERS } = require('opentracing');

function sayHello(helloTo, greeting) {

    const span = tracer.startSpan('say-hello');
    span.setTag('hello-to', helloTo);

    span.setBaggageItem('greeting', greeting)

    ns.run( () => {
github cesardeazevedo / sails-hook-sequelize-blueprints / test / fixtures / sampleapp / api / hooks / sequelize / index.js View on Github external
module.exports = function(sails) {
  global['Sequelize'] = require('sequelize');
  Sequelize.cls = require('continuation-local-storage').createNamespace('sails-sequelize-postgresql');
  return {
    initialize: function(next) {
      this.initAdapters();
      this.initModels();

      var connection, migrate, sequelize;
      sails.log.verbose('Using connection named ' + sails.config.models.connection);
      connection = sails.config.connections[sails.config.models.connection];
      if (connection == null) {
        throw new Error('Connection \'' + sails.config.models.connection + '\' not found in config/connections');
      }
      if (connection.options == null) {
        connection.options = {};
      }
      connection.options.logging = sails.log.verbose; //A function that gets executed everytime Sequelize would log something.
github ratneshsinghparihar / Node-Data / security / auth / principalContext.ts View on Github external
static getSession() {
        if (PrincipalContext.session != null && PrincipalContext.session != 'undefined') {
            //cls = require('continuation-local-storage').getNamespace;
            PrincipalContext.session = cls.getNamespace('session');
        } else {
            console.log('creating session from principal context');
            //cls = require('continuation-local-storage').createNamespace;
            PrincipalContext.session = cls.createNamespace('session');
        }
        return PrincipalContext.session;
    }
github otto-de-legacy / turing-microservice / turing-logging / lib / logger.js View on Github external
this.rewriters.push((level, msg, meta) => {
      const namespace = cls.getNamespace(config.get('turing:logging:namespace'));
      const request = namespace.get('request');
      const uuid = namespace.get('uuid');
      const metaFromConf = config.get('turing:logging:meta');

      if (uuid) {
        meta.uuid = uuid;
      }

      meta.caller = findCaller();

      if (request) {
        const headers = config.get('turing:logging:headers');
        headers.forEach((header) => {
          const value = request.headers[header];
          if (value) {
            meta[header] = value;
github alphagov / pay-selfservice / app / services / auth_service.js View on Github external
function deserializeUser (req, externalId, done) {
  const segment = new AWSXRay.Segment('deserialize')
  const namespace = getNamespace(clsXrayConfig.nameSpaceName)
  namespace.run(() => {
    namespace.set(clsXrayConfig.segmentKeyName, segment)
    AWSXRay.captureAsyncFunc('auth_service_deserializeUser', function (subSegment) {
      return userService.findByExternalId(externalId, req.headers[CORRELATION_HEADER] || '', subSegment)
        .then((user) => {
          segment.close()
          done(null, user)
        })
        .catch(err => {
          segment.close(err)
          logger.info(`[${req.correlationId}]: Failed to retrieve user, '${externalId}', from adminusers with statuscode: ${err.errorCode}`)
          done(err)
        })
    }, segment)
  })
}

continuation-local-storage

userland implementation of https://github.com/joyent/node/issues/5243

BSD-2-Clause
Latest version published 7 years ago

Package Health Score

74 / 100
Full package analysis