Skip to content

Commit

Permalink
Add runWithId function (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
puzpuzpuz committed Jun 10, 2020
1 parent e8f07cc commit 82e5ec5
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 3 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,30 @@ These are the available config options for the middleware/plugin functions. All
}
```

## Advanced features

In certain situations you may want to have an id available outside of the request handler scope, say, 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 @@ -22,8 +22,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 @@ -60,3 +58,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 @@ -7,6 +7,7 @@ const {
koaMiddleware,
koaV1Middleware,
hapiPlugin,
runWithId,
id
} = require('./src/middleware')

Expand All @@ -17,5 +18,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 @@ -16,6 +16,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 Down Expand Up @@ -81,6 +82,7 @@ const fastifyPlugin = ({

/**
* 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 @@ -107,6 +109,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 @@ -135,7 +138,8 @@ const koaV1Middleware = ({
}

/**
* 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 @@ -165,6 +169,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 @@ -178,5 +193,6 @@ module.exports = {
koaMiddleware,
koaV1Middleware,
hapiPlugin,
runWithId,
id
}
37 changes: 37 additions & 0 deletions tests/runwithid.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* 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(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
expect(id()).toEqual(42)
}, 42)
}

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

0 comments on commit 82e5ec5

Please sign in to comment.