rendom
rendom

Reputation: 3715

firebase functions chain middleware

Is there a way to chain middleware on "ordinary" firebase functions like in express?

"ordinary" function

addNote = https.onRequest((req, res, next) => {
 addNote(req, res,next);
});


using express I chained isAuthenticated and validate middleware

app.post("addNote", isAuthenticated, validate, (req, res, next) => {
  addNote(req, res, next);
 }
);

Upvotes: 3

Views: 1512

Answers (2)

Kevin Danikowski
Kevin Danikowski

Reputation: 5196

Here is a simple single handler function (reference answer)

const applyMiddleware = handler => (req, res) => {
  return middleware1(req, res, () => {
    return handler(req, res)
  })
}
exports.handler = functions.https.onRequest(applyMiddleware(handler))

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317750

The only way you can automatically apply express middleware is to create an Express app for an endpoint (or collection of endpoints) and apply middleware to it. That express app can then handle HTTP endpoints with Cloud Functions for Firebase. For example:

const cookieParser = require('cookie-parser')();
const cors = require('cors')({origin: true});
const app = express();

app.use(cors);
app.use(cookieParser);

app.get('/hello', (req, res) => {
  res.send(`Hello ${req.user.name}`);
});

exports.app = functions.https.onRequest(app);

Now the /hello function is served by Cloud Functions, and has the cors and cookie-parser middleware applied to it.

Code segment taken from this sample.

Upvotes: 5

Related Questions