Last active
June 23, 2022 19:47
-
-
Save sr2ds/a5dde2d674a24d6f9cbb862943632e5d to your computer and use it in GitHub Desktop.
Middleware to make logs for requests in NodeJs - ExpressJs
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
// Mongoose model to store logs | |
logModel = () => { | |
const db = require('../lib/db'); | |
const Schema = db.Schema; | |
const logsSchema = new Schema({ | |
method: { type: String, trim: true }, | |
url: { type: String, trim: true }, | |
query: { type: Object, }, | |
params: { type: Object, }, | |
body: { type: Object, }, | |
response: { type: Object, }, | |
key: { type: String, unique: true}, | |
}) | |
return db.model('Logs', logsSchema) | |
} | |
const model = logModel() | |
logRequests = async (req, res, next) => { | |
try { | |
const { query, params, body, originalUrl, method } = req; | |
let oldSend = res.send | |
res.send = async (data) => { | |
// @todo: implement not repetition validating key attribute | |
await new model({ | |
method, | |
url: originalUrl, | |
body, | |
query, | |
params, | |
response: JSON.stringify(data), | |
key: `${method}${originalUrl}${JSON.stringify(body)}${JSON.stringify(query)}${JSON.stringify(params)}` | |
}).save() | |
// console.log('REQUEST:', method, originalUrl, query, params, body) | |
// console.log('RESPONSE:', data) | |
res.send = oldSend | |
return res.send(data) | |
} | |
next() | |
} catch (error) { | |
console.log(error) | |
next() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment