Cloud functions are great way to operate a serverless backend. They are functions you can create with JS or typescript and then they are stored on google cloud to preform actions based off HTTP request or firebase features. They are pretty easy to setup, once you have everything setup its just a specific call to create a cloud function. Looks like this:
const functions = require("firebase-functions");
then
exports.functionName = functions.https.onRequest((request, response) => {})
After you create your function and set up what ever logic you want to happen, you'll then want to deploy your function up to firebase. As long as there are no errors in your code your function will now be hosted on google cloud/firebase. You'll be provided with a url that you can now send request to in order to preform the function you created.
Typically these cloud functions are going to be used for firebase features like authentication or google services like cloud storage. Here is an example function that will grab a specific user from our firestore collection of users.
exports.getUser = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const userId = request.body.userId;
const userRef = db.collection('users').doc(userId);
userRef.get()
.then(snapshot => {
if (snapshot.exists) {
response.send(snapshot.data())
} else {
response.send("User not found")
}
}).catch(error => response.send({errors: error}));
});
});
onRequest() allows you to use the cloud functions you create with http request. Giving us access to both the request and response. The request can be used to receive information that you might use in order to find specific data entry, for instance in the example above we grab the userId out of the request body. Then we are able to send back whatever information is needed back through the response with response.send().
These are the basics to firebase cloud functions. They can be really useful for working with a firebase project. There is very little maintenance required after creating them. It will take a little time to get use to working with them but once you do it seems to be pretty smooth sailing. Hope you were able to take away something from this and I hope you have a great day!
Top comments (0)