Created
July 11, 2021 01:08
-
-
Save selfagency/d7b4b7170361e6941cb082e023ded6e1 to your computer and use it in GitHub Desktop.
[express middleware boilerplate]
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
// the function that will transform the content or whatever | |
function myFunction (data, opts) { | |
// do your stuff here | |
return `${data}` | |
} | |
// the middleware that gets passed to app.use() | |
function myMiddleware (opts) { | |
// options passed to the middleware | |
// eg.: app.use(myMiddleware({opt1: "opt1", opt2: "opt2"}) | |
const default_opts = { | |
opt1: "opt1", | |
opt2: "opt2", | |
override: false | |
} | |
opts = opts || {} | |
opts = Object.assign(opts, default_opts) | |
// the response handler | |
function doThing (req, res, next) { | |
const theThing = function (data, opts, cb) { | |
if (typeof cb === 'undefined') { | |
// if no callback do this | |
return function (err, html) { | |
if (err) return next(err) | |
html = myFunction(data, opts) | |
res.send(html) | |
} | |
} else { | |
// if callback do this | |
return function (err, html) { | |
if (html) html = myFunction(data, opts) | |
cb(err, html) | |
} | |
} | |
} | |
// returns your middleware in stream | |
res.myMiddleware = function (view, renderOpts, cb) { | |
this.render(view, renderOpts, theThing(data, opts, cb)) | |
} | |
// returns your middleware only if explicitly called | |
if (opts.override) { | |
res.oldRender = res.render | |
res.render = function (view, renderOpts, cb) { | |
this.oldRender(view, renderOpts, theThing(data, opts, cb)) | |
} | |
} | |
return next() | |
} | |
return doThing | |
} | |
module.exports = myMiddleware |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment