Last active
January 24, 2018 01:17
-
-
Save Aupajo/d440cb13ee1ed5d41561439cad564efa to your computer and use it in GitHub Desktop.
Continuations in Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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