Skip to content

Instantly share code, notes, and snippets.

@Aupajo
Last active January 24, 2018 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aupajo/d440cb13ee1ed5d41561439cad564efa to your computer and use it in GitHub Desktop.
Save Aupajo/d440cb13ee1ed5d41561439cad564efa to your computer and use it in GitHub Desktop.
Continuations in Node
const { createNamespace } = require('continuation-local-storage')
const createUUID = require('uuid/v1')
// Application
const logger = require('./logger')
const performSomeProcessing = require('./processing')
// Establish a new storage area for the continuation
const context = createNamespace('context')
function ingestMessageFromKafka(message) {
context.set('uuid', `O-${createUUID()}`)
// The logger automatically tags the message with the UUID
logger.info("Doing something with the offer")
// Methods called inside this method will also be aware of the context,
// but the context is scoped within the call stack (this applies to async
// callbacks, too)
performSomeProcessing()
}
context.run(ingestMessageFromKafka, { type: "offer", id: 432 })
// Outputs:
// [info] [O-10726890-00a4-11e8-a730-1143f88b51b3] Doing something with the offer
// [info] [O-10726890-00a4-11e8-a730-1143f88b51b3] Performing some processing
const { getNamespace } = require('continuation-local-storage')
function formatTags(...tags) {
return tags.map(tag => `[${tag}]`).join(' ')
}
module.exports = {
device: console,
info(...args) {
const uuid = getNamespace('context').get('uuid')
const tags = ['info', uuid]
this.device.log(formatTags(...tags), ...args)
}
}
const logger = require('./logger')
module.exports = function() {
// Will still be tagged with the context, even though this file knows nothing about the tags
logger.info("Performing some processing")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment