Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Making it possible to add custom request properties to CLS namespace. #25

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ export interface IOptions {
useHeader?: boolean
// Default: 'X-Request-Id'
headerName?: string
// Default: undefined
customNamespacePropertiesBuilder?: (request: any, namespace: any) => void
}

export interface IHapiPlugin<T> {
Expand Down
30 changes: 25 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ const uuidv1 = require('uuid/v1')
const nsid = `rtracer:${uuidv1()}`
const ns = cls.createNamespace(nsid)

const setupCustomNamespaceProperties = (customNamespacePropertiesBuilder, req) => {
if (customNamespacePropertiesBuilder) {
customNamespacePropertiesBuilder(req, ns)
}
}

/**
* Generates a request tracer middleware for Express.
* @param {Object} options possible options
Expand All @@ -17,7 +23,8 @@ const ns = cls.createNamespace(nsid)
*/
const expressMiddleware = ({
useHeader = false,
headerName = 'X-Request-Id'
headerName = 'X-Request-Id',
customNamespacePropertiesBuilder = undefined
} = {}) => {
return (req, res, next) => {
ns.bindEmitter(req)
Expand All @@ -31,6 +38,7 @@ const expressMiddleware = ({

ns.run(() => {
ns.set('requestId', requestId)
setupCustomNamespaceProperties(customNamespacePropertiesBuilder, req)
next()
})
}
Expand All @@ -46,7 +54,8 @@ const expressMiddleware = ({
*/
const koaMiddleware = ({
useHeader = false,
headerName = 'X-Request-Id'
headerName = 'X-Request-Id',
customNamespacePropertiesBuilder = undefined
} = {}) => {
return (ctx, next) => {
ns.bindEmitter(ctx.req)
Expand All @@ -60,6 +69,7 @@ const koaMiddleware = ({

return new Promise(ns.bind((resolve, reject) => {
ns.set('requestId', requestId)
setupCustomNamespaceProperties(customNamespacePropertiesBuilder, ctx.req)
return next().then(resolve).catch(reject)
}))
}
Expand All @@ -75,7 +85,8 @@ const koaMiddleware = ({
*/
const koaV1Middleware = ({
useHeader = false,
headerName = 'X-Request-Id'
headerName = 'X-Request-Id',
customNamespacePropertiesBuilder = undefined
} = {}) => {
return function * (next) {
ns.bindEmitter(this.req)
Expand All @@ -90,6 +101,7 @@ const koaV1Middleware = ({
}
requestId = requestId || uuidv1()
ns.set('requestId', requestId)
setupCustomNamespaceProperties(customNamespacePropertiesBuilder, this.request)

yield next
} finally {
Expand All @@ -110,7 +122,8 @@ const hapiPlugin = ({
register: async (server, options) => {
const {
useHeader = false,
headerName = 'X-Request-Id'
headerName = 'X-Request-Id',
customNamespacePropertiesBuilder = undefined
} = options

server.ext('onRequest', (request, h) => {
Expand All @@ -130,6 +143,7 @@ const hapiPlugin = ({
}
requestId = requestId || uuidv1()
ns.set('requestId', requestId)
setupCustomNamespaceProperties(customNamespacePropertiesBuilder, request)

return h.continue
})
Expand All @@ -146,11 +160,17 @@ const hapiPlugin = ({
*/
const id = () => ns.get('requestId')

/**
* Returns property's value or `undefined` in case if the call is made from an outside CLS context.
*/
const getNamespaceProperty = (propertyName) => ns.get(propertyName)

module.exports = {
expressMiddleware,
fastifyMiddleware: expressMiddleware,
koaMiddleware,
koaV1Middleware,
hapiPlugin,
id
id,
getNamespaceProperty
}
27 changes: 27 additions & 0 deletions tests/express.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,31 @@ describe('cls-rtracer for Express', () => {
expect(id1).not.toEqual(id2)
})
})

test('generates custom namespace property for request', () => {
const app = express()
const propertyName = 'originalUrl'

app.use(rTracer.expressMiddleware({
customNamespacePropertiesBuilder: (request, namespace) => {
namespace.set(propertyName, request.originalUrl)
}
}))

let propertyValue

const requestUrl = '/test'
app.get(requestUrl, (req, res) => {
propertyValue = rTracer.getNamespaceProperty(propertyName)
res.json({ propertyValue })
})

return request(app).get(requestUrl)
.then(res => {
expect(res.statusCode).toBe(200)
expect(propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue.length).toBeGreaterThan(0)
})
})
})
27 changes: 27 additions & 0 deletions tests/fastify.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -253,4 +253,31 @@ describe('cls-rtracer for Fastify', () => {
expect(id1).not.toEqual(id2)
})
})

test('generates custom namespace property for request', () => {
const app = Fastify()
const propertyName = 'originalUrl'

app.use(rTracer.expressMiddleware({
customNamespacePropertiesBuilder: (request, namespace) => {
namespace.set(propertyName, request.originalUrl)
}
}))

let propertyValue

const requestUrl = '/test'
app.get(requestUrl, async (_, reply) => {
propertyValue = rTracer.getNamespaceProperty(propertyName)
reply.send({ propertyValue })
})

return app.ready().then(() => request(app.server).get('/test'))
.then(res => {
expect(res.statusCode).toBe(200)
expect(propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue.length).toBeGreaterThan(0)
})
})
})
33 changes: 33 additions & 0 deletions tests/hapi.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ const setupServer = async ({
handler
})

server.route({
method: 'GET',
path: '/test',
handler
})

await server.register({
plugin: rTracer.hapiPlugin,
options
Expand Down Expand Up @@ -243,4 +249,31 @@ describe('cls-rtracer for Hapi', () => {
expect(res2.result.id).toEqual(ids['id2'])
expect(res1.result.id).not.toEqual(res2.result.id)
})

test('generates custom namespace property for request', async () => {
const propertyName = 'originalUrl'
let propertyValue
server = await setupServer({
options: {
customNamespacePropertiesBuilder: (request, namespace) => {
namespace.set(propertyName, request.path)
}
},
handler: () => {
propertyValue = rTracer.getNamespaceProperty(propertyName)
return { propertyValue }
}
})

const requestUrl = '/test'
const res = await server.inject({
method: 'get',
url: requestUrl
})

expect(res.statusCode).toBe(200)
expect(propertyValue).toEqual(requestUrl)
expect(res.result.propertyValue).toEqual(requestUrl)
expect(res.result.propertyValue.length).toBeGreaterThan(0)
})
})
27 changes: 27 additions & 0 deletions tests/koa.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,31 @@ describe('cls-rtracer for Koa', () => {
expect(id1).not.toEqual(id2)
})
})

test('generates custom namespace property for request', () => {
const app = new Koa()
const propertyName = 'originalUrl'

app.use(rTracer.koaMiddleware({
customNamespacePropertiesBuilder: (request, namespace) => {
namespace.set(propertyName, request.url)
}
}))

let propertyValue

const requestUrl = '/test'
app.use((ctx) => {
propertyValue = rTracer.getNamespaceProperty(propertyName)
ctx.body = { propertyValue }
})

return request(app.callback()).get(requestUrl)
.then(res => {
expect(res.statusCode).toBe(200)
expect(propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue.length).toBeGreaterThan(0)
})
})
})
27 changes: 27 additions & 0 deletions tests/koav1.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,4 +185,31 @@ describe('cls-rtracer for Koa v1', () => {
expect(id1).not.toEqual(id2)
})
})

test('generates custom namespace property for request', () => {
const app = new Koa()
const propertyName = 'originalUrl'

app.use(rTracer.koaV1Middleware({
customNamespacePropertiesBuilder: (request, namespace) => {
namespace.set(propertyName, request.url)
}
}))

let propertyValue

const requestUrl = '/test'
app.use(function * () {
propertyValue = rTracer.getNamespaceProperty(propertyName)
this.body = { propertyValue }
})

return request(app.callback()).get(requestUrl)
.then(res => {
expect(res.statusCode).toBe(200)
expect(propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue).toEqual(requestUrl)
expect(res.body.propertyValue.length).toBeGreaterThan(0)
})
})
})