Skip to content

Instantly share code, notes, and snippets.

@Aupajo Aupajo/app.js
Last active Jan 24, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.