Skip to content

Commit

Permalink
Merge 3e8c160 into f92c7f9
Browse files Browse the repository at this point in the history
  • Loading branch information
puzpuzpuz committed Jun 10, 2020
2 parents f92c7f9 + 3e8c160 commit 5731cd1
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 3 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,30 @@ These are the available config options for the middleware functions. All config
}
```

## Advanced features

In certain situations you may want to have an id available in the scope of an arbitrary function, e.g. in a code that acts as a background job. In this case you may use the `runWithId()` function:

```js
const rTracer = require('cls-rtracer')

rTracer.runWithId(() => {
console.log(rTracer.id()) // id is available here
setInterval(() => {
console.log(rTracer.id()) // and here
}, 1000)
})

// you may override id by providing the 2nd argument
rTracer.runWithId(() => {
// ...
}, 42) // 42 is the id override here

// async/await syntax is also supported, as `runWithId()`
// returns the result of `fn`
await rTracer.runWithId(myAsyncFn)
```

## Troubleshooting

To avoid weird behavior:
Expand Down
6 changes: 4 additions & 2 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ export interface IHapiPlugin<T> {
register: (server: any, options: T) => void | Promise<void>
}

export declare const id: () => string | undefined

export declare const expressMiddleware: (
options?: IOptions,
) => (
Expand Down Expand Up @@ -43,3 +41,7 @@ export declare const koaV1Middleware: (
) => GeneratorFunction

export declare const hapiPlugin: IHapiPlugin<IOptions>

export declare const runWithId: (fn: Function, id?: any) => any

export declare const id: () => string | undefined
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
koaMiddleware,
koaV1Middleware,
hapiPlugin,
runWithId,
id
} = require('./src/middleware')

Expand All @@ -15,5 +16,6 @@ module.exports = {
koaMiddleware,
koaV1Middleware,
hapiPlugin,
runWithId,
id
}
18 changes: 17 additions & 1 deletion src/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const wrapHttpEmitters = (req, res) => {

/**
* Generates a request tracer middleware for Express.
*
* @param {Object} options possible options
* @param {boolean} options.useHeader respect request header flag
* (default: `false`)
Expand All @@ -40,6 +41,7 @@ const expressMiddleware = ({

/**
* Generates a request tracer middleware for Koa v2.
*
* @param {Object} options possible options
* @param {boolean} options.useHeader respect request header flag
* (default: `false`)
Expand All @@ -66,6 +68,7 @@ const koaMiddleware = ({

/**
* Generates a request tracer middleware for Koa v1.
*
* @param {Object} options possible options
* @param {boolean} options.useHeader respect request header flag
* (default: `false`)
Expand Down Expand Up @@ -96,7 +99,8 @@ const koaV1Middleware = ({
const pluginName = 'cls-rtracer'

/**
* A request tracer plugin for Hapi
* A request tracer plugin for Hapi.
*
* @type {{once: boolean, name: string, register: hapiPlugin.register}}
*/
const hapiPlugin = ({
Expand Down Expand Up @@ -126,6 +130,17 @@ const hapiPlugin = ({
}
})

/**
* Runs the given function in scope of the id.
*
* @param {Function} fn function to run
* @param {*} id optional id to be available in the function
*/
const runWithId = (fn, id) => {
id = id || uuidv1()
return als.run(id, fn)
}

/**
* Returns request tracer id or `undefined` in case if the call is made from
* an outside CLS context.
Expand All @@ -138,5 +153,6 @@ module.exports = {
koaMiddleware,
koaV1Middleware,
hapiPlugin,
runWithId,
id
}
36 changes: 36 additions & 0 deletions tests/runwithid.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* global describe, test, expect */
'use strict'

const { runWithId, id } = require('../src/middleware')

describe('runWithId', () => {
test('runs function in scope of generated id', (done) => {
expect(id()).toBeUndefined()

runWithId(() => {
const availableId = id()
expect(availableId.length).toBeGreaterThan(0)

setTimeout(() => {
expect(id()).toEqual(availableId)
done()
}, 0)
})
})

test('runs function in scope of overriden id', () => {
runWithId(() => {
expect(id()).toEqual(42)
}, 42)
})

test('supports awaiting the function', (done) => {
async function asyncFn () {
await runWithId(() => {
expect(id()).toEqual(42)
}, 42)
}

asyncFn().then(done).catch(done)
})
})

0 comments on commit 5731cd1

Please sign in to comment.