Skip to content

Instantly share code, notes, and snippets.

@tomardern
Created October 22, 2017 16:39
Show Gist options
  • Save tomardern/822b1e9579908639a37f919021e0d108 to your computer and use it in GitHub Desktop.
Save tomardern/822b1e9579908639a37f919021e0d108 to your computer and use it in GitHub Desktop.
Express Function Logging in Firebase functions
const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
/**
* Route all firebase function requests through to express
* See https://codeburst.io/express-js-on-cloud-functions-for-firebase-86ed26f9144c
*/
const app = express();
app.use(cors({ origin: true }));
app.use(bodyParser.json());
/**
* This creates both express routes and google cloud routes
* The name changes eg /hello-world/here becomes get_helloworld_here
*/
const route = (method, uri, fn) => {
var key = uri.replace(/[^\w\-\_\/]/g, '').replace(/-/g, '').replace(/\//g, '_');
exports[method + key] = functions.https.onRequest(fn);
app[method](uri, exports[method + key]);
};
/**
* Our routes
*/
route('get', '/hello-tom', (request, response) => {
response.send('hello tom!');
});
route('get', '/hello-world', (request, response) => {
response.send('hello world!');
});
route('get', '/hello-there', (request, response) => {
response.send('hello there!');
});
/*
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
*/
/**
* Finally, mount the express app to /api/*
*/
exports.api = functions.https.onRequest((request, response) => {
if (!request.path) {
request.url = `/${request.url}` // prepend '/' to keep query params if any
}
return app(request, response)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment