Last active
March 1, 2020 11:02
-
-
Save diroussel/e6bf15c029beb0903057d2d6cdebf86a to your computer and use it in GitHub Desktop.
node server with correlationId pass though
This file contains hidden or 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 express = require('express'); | |
const bodyParser = require('body-parser'); | |
const pino = require('express-pino-logger'); | |
const uuid = require('uuid'); | |
const axios = require('axios'); | |
const app = express(); | |
const port = 3000; | |
function correlationIdMiddleware (options) { | |
const headerName = (options && options.header) || 'x-correlation-id'; | |
return (req, res, next) => { | |
const id = req.get(headerName); | |
req.correlationId = id || uuid.v4(); | |
next(); | |
}; | |
} | |
app.use(correlationIdMiddleware()); | |
app.use(pino({ | |
genReqId: (req) => { | |
return req.correlationId; | |
} | |
})); | |
app.use(bodyParser.json()); | |
const someService = async (log, httpClient, data) => { | |
const transformed = { | |
...data, | |
somethingElse: 'hi' | |
}; | |
log.info('getting some data'); | |
const result = await httpClient.post('https://postman-echo.com/post', transformed); | |
log.info('got some data'); | |
return result.data; | |
}; | |
const createHttpClient = (log, request) => { | |
const { correlationId } = request; | |
const instance = axios.create({ | |
headers: {'x-correlation-id': correlationId} | |
}); | |
instance.interceptors.request.use(request => { | |
log.info(request); | |
return request | |
}); | |
instance.interceptors.response.use(response => { | |
// might need to change this as | |
// response has a lot of crap on it | |
log.info(response); | |
return response | |
}); | |
return instance; | |
}; | |
app.get('/', async (req, res) => { | |
const { log } = req; | |
const httpClient = createHttpClient(log, req); | |
let transformedData; | |
try { | |
transformedData = await someService(log, httpClient, req.body); | |
} catch (e) { | |
log.error(e); | |
return res.status(500).json({ | |
message: 'Sorry an error has occurred' | |
}); | |
} | |
return res.json(transformedData); | |
}); | |
app.listen(port, () => console.log(`Example app listening on port ${port}!`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment