Last active
September 28, 2017 20:25
-
-
Save scwood/2b68967d7203d463f421166ffdcb6a94 to your computer and use it in GitHub Desktop.
How to call express middleware in a Google Cloud Function
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
| function cors(req, res, next) { | |
| console.log('in cors middleware:'); | |
| req.cors = 'enabled'; | |
| console.log(req); | |
| next(); | |
| } | |
| function logger(req, res, next) { | |
| console.log('in logger middleware:'); | |
| req.logged = true; | |
| console.log(req); | |
| next(); | |
| } | |
| function doStuff(req, res) { | |
| console.log('in final handler:'); | |
| req.sent = 'data'; | |
| console.log(req); | |
| } | |
| function callMiddleware(req, res, middleware) { | |
| if (middleware.length === 0) { | |
| return; | |
| } | |
| const currentMiddleware = middleware.shift(); | |
| currentMiddleware(req, res, () => callMiddleware(req, res, middleware)); | |
| } | |
| // function deployed to GCF | |
| module.exports.handler = function(req, res) { | |
| callMiddleware(req, res, [cors, logger, doStuff]); | |
| }; | |
| module.exports.handler({}, {}); | |
| // $ node gcloud-express-middleware.js | |
| // in cors middleware: | |
| // { cors: 'enabled' } | |
| // in logger middleware: | |
| // { cors: 'enabled', logged: true } | |
| // in final handler: | |
| // { cors: 'enabled', logged: true, sent: 'data' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment