Last active
September 10, 2023 16:58
-
-
Save RealBeepMcJeep/86eca98bef2861438da75375797633fe to your computer and use it in GitHub Desktop.
used for hijacking jsonParser middleware and dumping the request/response bodies to text files; used with https://jvilk.com/MakeTypes/ to RE an API endpoint (black-box) and begin documenting/refactoring. especially helpful for monolith applications.
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 _jsonParser = express.json({ limit: '100mb' }); | |
// hijack jsonParser to log JSON bodies | |
console.log('installing jsonParser hijack') | |
const jsonParser = (req, res, next) => { | |
console.log('jsonParser called @', req.method, req.url); | |
_jsonParser(req, res, (next_retval) => { | |
// log if JSON request | |
if (req.headers && req.headers['content-type'] && req.headers['content-type'].startsWith('application/json') && req.body) { | |
let fname = `${humanizedISO8601DateTime()}-${req.url.replace(/\//g, '')}.json`.replace(/ /g, '_') | |
let _path = path.join(__dirname, 'debugLogs', fname) | |
console.log('logging to', _path) | |
console.log('request was application/json', JSON.stringify(req.body).length, 'bytes') | |
try { | |
console.log('writing', _path) | |
fs.writeFileSync(_path, JSON.stringify(req.body, null, 2)) | |
console.log('did write', _path) | |
} catch (e) { | |
console.log('failed to write', _path, e) | |
} | |
let resp_fname = `${humanizedISO8601DateTime()}-${req.url.replace(/\//g, '')}-response.json`.replace(/ /g, '_') | |
let resp_path = path.join(__dirname, 'debugLogs', resp_fname) | |
var oldWrite = res.write, | |
oldEnd = res.end; | |
var chunks = []; | |
res.write = function (chunk) { | |
chunks.push(chunk); | |
return oldWrite.apply(res, arguments); | |
}; | |
res.end = function (chunk) { | |
if (chunk) | |
chunks.push(chunk); | |
var body = Buffer.concat(chunks.map(chunk => typeof chunk === 'string' ? new Buffer(chunk) : chunk)).toString('utf8'); | |
// console.log(req.path, body); | |
fs.writeFileSync(resp_path, body) | |
oldEnd.apply(res, arguments); | |
}; | |
} | |
// console.log(req.headers) | |
next(next_retval) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment