Introduction:
Firebase, Backend as a service, released a new feature Cloud Functions. It allows developers write back-end code without worrying handling a server. In the following blog post, I explored how fast it is to create a simple HTTP request listener.
1. Install the Firebase CLI tools:
npm install -g firebase-tools
2. Login with Google account:
firebase login
3. Initialize a Firebase project:
firebase init
4. Select features with number keys [1,2,3]:
5. Select Firebase project:
After the initialization, the following files structure will be created:
The Cloud Functions can then be defined in the index.js file. Note that ES6 is used.
6. Deploy the functions:
7. Test it!
The Firebase console should show the deployed function:
And it can be tested via postman:
8 Different Request Methods
Different HTTP methods (GET POST etc.) of a route can be defined as follows:
9. Refactoring
Having many functions in one index.js file is not desired. Therefore I created Handler classes for handling logic.
Index.js (managing all the routes):
// imports const functions = require('firebase-functions'); // handlers const HellowordHandler = require('./handlers/helloword'); const hellowordHandler = new HellowordHandler('DEV'); // routes exports.helloWorld = functions.https.onRequest(hellowordHandler.handle.bind(hellowordHandler));
helloword.js (the logic in ES6 class):
class HelloWordHandler { constructor(env) { console.log(`Env: ${env}`); } handle(request, response) { switch (request.method) { case 'GET': this.getRequest(request, response); break; case 'POST': this.postRequest(request, response); break; default: response.status(403).send('Not support.'); break; } } getRequest(request, response) { response.send('GET request'); } postRequest(request, response) { console.log(request.body); response.send(request.body); } } module.exports = HelloWordHandler;
In this way, we can separate different logic to multiple files. In this just my first try to refactor it, if anyone has any suggests, please feel free to leave a comment :D.
How did you manage to have es6 with firebase ?
LikeLiked by 1 person
Sorry for the late reply, I think it can run ES6 directly. If you want more features which are not yet supported by the node natively, such as async await, you can try Webpack, Babel.
LikeLike