Firebase Cloud Functions Tutorial + Realtime Database Extension!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys and welcome back to you Nico day today we will make a tutorial and talk about cloud functions trial function is basically a back-end for firebase that will let you deploy JavaScript code on to firebase and then run it whenever you want now whether I divided this video in three different parts which are basically three different kind of function the first function is going to be a function you can call by just going to a certain URL so it's just going to be an endpoint the second function instead is going to be a function that is getting triggered when you change some data on the database so as soon as you change some data at a specific spot that function will get triggered and then the third function is going to be a scheduling function so a function that runs let's say every hour or every minute or every day or every Tuesday with that said we can begin but before beginning have you left alike yet on the video or subscribe if you're new really if you do any of those things you would support the channel so much and also leave in the comments any ideas you want for the future keep in mind this idea these videos that I'm doing right here was suggested by a few of you guys and this is why I'm making it so you know it's important for me to know what content you want to see next and on that note my next video will probably be something about a multiplayer system in firebase because so many people are stuck on this and really want to make something fun and multiplayer using firebase real-time database so this is something we will look into for the next video all right so let's begin ok so this is my file manager and I created a folder which is cloud functions tutorial we can open a terminal inside of here and here we can initialize our firebase now in order to do this I already said in another video you actually need to the firebase command and you can download that using NPM by doing I believe NPM install firebase tools something like that but if this is not the exact command I'm going to leave a link in the description for you to check out ok but if we do firebase in it we are going to initiate an instance of firebase and it's going to ask us what we want to put into this now if you watched my latest video on firebase and liters you can remember we actually use this to set and leaders but today we only care about functions so we're gonna trigger this on by clicking space or pressing space and then doing enter then we can select either an existing project or a new project this is going to go through your firebase project I'm just going to use a test one for this one and then it will tell us which language to use when I told you that this was a back-end in JavaScript I kinda lied because you can also do it in typescript but typescript is actually pretty close to JavaScript it's just an improved version that you can also use but you know for simplicity I'm gonna skip stick for simplicity I'm going to stick to JavaScript and then I'm going to do it yes because this is helpful and also I'm going to install the dependency and this this is not going to take longer but I will skip it there you go and now we are done we can start writing anything we want we can start writing any function we want with just that command alright so if we go back to our folder you can see that we have this stuff right here alright what you actually need to do is just go in the functions folder and as you can see right here you have everything you need what you actually need to modify is the index dot JavaScript file so we can open this with visual studio code this is the place where your cloud functions will stay now as you can see we already have a default cloud functions and we're gonna use that in just a moment let me just uncomment it okay and just do this now you don't need to know what any of these code does even if it's pretty straightforward but since it's just full code I'm going to just uncomment it and now save the file now this function is currently in my index dot java script but it's local if I want to deploy this change I have to go back to my terminal which if you remember is in my cloud function tutorial and for initiating everything that is firebase in it but now I just need to do firebase deploy and it is going to deploy my functions as well as anything else that I have set up in this folder like database rules or Austin websites but not only we only set up functions because this to this tutorial is mainly on functions so you know it's going to deploy the functions this is not going to take long as you can see is going to be creating a new No for functions and a second's he created this new function which is our hello world function which is this one right here now as soon as he finishes deploying this if this deployed correctly it will give us actually a link where we can call this function so this function is basically an endpoint so this is the first type of function it doesn't really matter right now we are going to describe later the three different kind of functions I'm going to show in this tutorial but right now we are just deploying a test function just to show you that it works come on firebase don't leave me hanging like this this is nerve-racking come on it usually doesn't take this long guys we're okay there you go it's done and now we have this link right here okay that we can open thanks to our terminal and as you can see if we go to this link this is actually a web page okay that you can go you can test this out and if you go to this link you will get this response which is hello from firebase and if we go back to our function as you can see this is basically exactly what it does it setups a new function which is the other word function and it's a function which is type on request and it's going to send us a response which is hello from firebase which is this string of text right here so there you go our first function was correctly set up and we also know now how to call these functions naturally if you need to call this function from any place or from any app you can just do a get request to this URL and you're going to get to be sold now an example I can try doing this via terminal I can do C URL and then just this and I'm going to get back hello from firebase I know that is also a firebase functions SDK for some services such as unity that allows you to call functions more easily but you know it's as easy as doing a request to this website so I don't know what additional functionalities the SDK adds but we're not going to show that in this tutorial okay so we already got a little bit of a spoiler on what the first type of function is now as you can see this function as two parameters our request and our response you know as a test I'm going to change this function already I will keep this function okay this function can stay okay this is pretty fun we're gonna actually copy it and create a different function I'm going to call this function string two lengths okay I'm really good at giving names to function this is a function I will always remember or actually let's call it text to act okay much better all right so as you can see as a parameter of this function we have the request and the response basically the request will give us any information that the client has given us during the request so at example if it's a post request from the request we can get actually the body so if I go right here and do request dr. you can see that I can get a lot of stuff so I can get the body of the request I can get the state of the request I can get that URL of the request not sure why that would be a thing that I want I can get the others of the request which is something that I might also need and we're gonna use them right now I can also get the queries of the request basically what I want to do is I'm going to give this function R strained okay and this function will return me the length of the string pretty straightforward we already know from this example how to make the function return something which is response dub sound and then whatever we want to sign it okay okay but first of all from the request we have to actually retrieve the original text that we want to know the length all so we're going to go up our text equal request dot query and now basically this query is a dictionary string string so right here we could input anything we want like an example text and this is basically going to be the name of the query and we're gonna get the value of this query if it's not know so the text is going to be this and then we're gonna do a new variable which is text length which is basically just going to be text dot light pretty straightforward and then we're gonna do response dot send text length all right so we save and then we go back to our terminal and deploy the function again one thing to keep in mind is that now we have both of the functions deployed because as you can see whoops that's my OBS I didn't want to show that but as you can see the index of JavaScript as both of functions if I were to remove this function and then hit save it would actually remove the function from the cloud functions once I hit deploy all right so now that our function was correctly deployed and this is the URL by the way the URL is always the same for your project the only part that changes is the slash and right here this is the name of the function so the name of our previous function was zero hello world the name of this function is going to be text length so I can just do text today and as you can see it will return me oh it will return me an error ha ha I see what the problem is so right here responded saying that only accepts a string but beforehand I was actually passing an integer because the text length is an integer so it didn't understand what I was you know sending and it was I was sending an error code so that is why it was giving me this problem but anyway lesson learned so I just need to I can just concatenate the string like this so it will pass this as a string I have ready deploy to the new version but it is actually really good that I made this mistake because now if you go to functions right here you click on functions in your project you can actually see a dashboard of all of the functions that we published and you can also see the logs so where it's going to tell you the various exceptions that happened either while deploying but also when running the function so as you can see here we have a bunch of different errors from me trying to function a bunch of times and as you can see you will give me a range error invalid status code for because I gave this function of text which was test the length of test is 4 and right here I was citing 4 and he considered for us an error code and it was an invalid error code so he gave me this exception you can also see that if I don't input anything as a query I will still get an error and if I go to the console I will get this error which is cannot read property length of undefined because naturally I didn't insert any queries but if right here I do text equal at example text 1 2 3 4 I'm going to get 8 because the the length of test 1 2 3 4 is a so great the function is running correctly now probably one thing you could do is do a check if this query is undefined or not and if it is just return ever because right now we're not doing any check for exceptions so it's just dying horribly but other than that this function is done all right great so now we know how to properly setup a function with a URL endpoint all right so now we're going to learn how to extend cloud functions into our firebase real-time database aka we're going to create a function that is going to get run automatically when something on the database changes I will leave in the description this page which is in the docs page which will teach you how to exactly do that and give you information on the code itself ok so this is the formatting for our new function as you can see is the same for our old ones but instead of being functions doctor HTTP on request is going to be functions dot database dot read and this basically means this function will be called when this kind of path changes and now we can put any path we want right here and it's going to be a path to our database so if we go back to our database itself let's remove this thing and let's add maybe a user folder ok and right here we can add I mean we're not gonna we're just gonna add one user as a test is gonna be user 1 maybe it's going to have a name surname and nickname okay and okay this could be ABC now I want to test for when a user has changed its name so we're gonna go right here we're gonna do a new node detected functions the database not rest we have to go first in users and I don't need the quotes okay because there are already the single quotation marks okay then I have to go to user 1 okay now that is one small problem okay I don't want to know if user 1 has changed this name but what I want to know is if any user has changed their name so an example I could have a user - they just updated his name - I don't know sad ok that's the first or are maybe simply happier ok maybe ABC so right here in the path instead of putting user 1 you just boot using this format right here I could put a generic user ID and what this basically means is it will check for any user that change this name so as you can see in the dog so we actually have all four of the methods explained and you can use these for any sign and against that you want so the oncreate method will trigger when you know some data is created so the data at that location was normal and now it's something instead on delete we'll do the opposite so when the data goes back to no then it will trigger an update instead will trigger only when the data changed from something to something and instead unright will be triggered always so either the data change to no change the from null or changed from something all right doesn't care it will just always trigger now for our initial condition we're going to use all create which means that the function will trigger only when the user adds is named to the database but if he changes it later is not going to trigger all right so now right here we have a snapshot as a parameter and the snapshot is basically a data snapshot of this branch so using this parameter we can get information on the name branch and the name value so by just doing snapshot to total value this is going to be the name of the user so if I do if our name equals this and the user changes its name to ABC this variable will be ABC okay so for testing I can just do console log good name and we're going to see the name in the logs on firebase okay also one thing to keep in mind and which is actually pretty good is that right here when you're deploying it will actually give you any warning or exceptions that you know don't make your code run and right here that example it gave me a warning that instead of using the coercion or whatever I was using right here for this function what I could basically do is just to string this and this will basically come convert to my number into a string and you know firebase actually suggested me this alright well now we have actually deployed so this function should be live as you can see successful create operation right here okay and we created our new node detected function which probably is not a good name for it but now if I go right here and now keep in mind this function will only trigger when I create some data so I'm going to create a user tree okay we're not going to set the name just yet we're gonna just set the surname an example which is going to be B and as you can see nothing will trigger but if on user 3 I also add a name which is test name the function will actually run and now to see that this function has run I can go into the logs there you go my function as run and you return me test name which is basically this console of T you can also see that there was an exception and the reason for that is because we actually didn't return anything to the function so it was giving an exception because the function returns undefined but we actually don't care about that all we care about is that we got the correct information which is test name now one thing to note is that this stuff is not shot naturally it doesn't have to be just one value it could also contain children for example you can do dog child and you can get a specific children but yeah for this example the value is just the name of the user is just a string but it could be a more complex object that is on firebase by an now that that is done what if we want to get back the user ID that set this name keep in mind right now we only have information about the name of the user but we don't have information about what the user ID of that user is so as you can see in the URL I used this special form to indicate that you know it could be any user any user ID will do I could actually retrieve this specific user ID for the specific change when I run this function and the way I do that is using this context parameter so I could do a new variable which is user ID and this one will just be context dot and as you can see we can get a lot of information about when the request was made at example but also also the event type so if it's a right event it's an update event or on create event but what we need right now is just the parameters dictionary and in the parameters we can just put the user ID parameter and this will give us back the user ID of the user just with magic so right now in the console log I could write it's not just writing the name I could say user ID change the its name - there you go I just need to add some sweetness to it so it looks nice now before deploying I actually want to do one last change as of right now we are using the function on create so this means that this function will only be called when we create a new data so if a user changes its name this function will actually not be cold and we don't want that we actually want this function to always run as soon as an user changes its name this function has to run so instead of on create we are going to use on right now on right and on update actually have a tiny little bit of a change in the parameters of the function instead of being a snapshot and a context right here instead of the snapshot parameter we are going to have a change parameter and basically a change parameter basically contains two different snapshots it contains the front in the snapshot before an update was made and the snapshot after an update was made so we know how the data was before the user changed it and how it is now after the user changed it so right here let's add another variable which is okay let's rename this to previous name okay and is going to be B or we could call it old name and it could just be change dot before dot value and then we're going to have the new name which is going to be changed after dot value all right so now right here we can say you sir change a user ID changed its name from the old one to the new one and now we're gonna know all of the information we need we know who did this change we know what was the name before and this is probably gonna be know if the name was nothing before so you probably have to do some checks on that and then is going to give us the new name of the user so this is great all right and now let's see if it works we have test name right here on user 3 and we're going to update it to new name maybe spelled correctly and as you can see we actually updated it and if we go right here in the logs in awhile we will get the new logs that it will tell us the exactly the information we want hopefully now you might say it's taking a little bit of a while actually between the logs and this is normal but the function is actually executing instantly it just takes a while to get the logs and there you go as you can see the log is telling me user tree change this name from test name to new name so this works now before going to our third type of function which is basically a scheduling function I want to show you just how instantly this update happens in order to show you that I actually want to push back some data on the database so when the user changes his name I want to function to post some data somewhere else on the database and in order to do that it's actually really really simple I can just use the admin SDK in order to do that right here I have to create a new constant called admin that we require the firebase admin SDK you know what this administered us especially on the database because it actually can access different services such as both or even firestore okay in order to set it up we just have to do this which is basically going to initialize our admin app using the config which is already in the firebase function and then right here we can have a variable which is just going to be our database admin SDK which is gonna be the admin doc database okay and down here instead of doing console.log we can just do database dot ref and here put the place where we want to post the information into which in my case just making stuff up can be meta data okay and then last change the name and we're gonna put it right here and then I'm gonna do dot site and inside these parentheses we have to put the object that we want set which in our case it will be a string and will be this string right here BAM okay so in theory if I deploy now it should work alright and now if we do the exacting test again but we do it on use of Choo and we call this CBA it's going to create a new thing which is metadata okay and it's going to add last change the name and as you can see the value will be user to change this name from ABC NCBA and you can see out fast disk was so as you can see boom and a one two in two seconds you just deploy this so this is pretty fun okay and the last thing I wanted to show you in this pretty long video I just realized is the scheduling functions okay luckily for us the syntax for doing schedule it functions is really simple so right here we have our new function and it's going to be a functions dot pub/sub this time dot schedule and right here you can input as a string how often you want your function to run now that is actually a syntax for pops up and I'm going to leave a link in the description to the syntax so you can check it out but basically you can write every 60 cycles or every 60 minutes or even every day or every day at a certain time I believe and it will run the function exactly at that time every day so in my case I want to make it run every 60 seconds and just for testing this function will run every 60 seconds so every 60 seconds I want something to be updated on the data means I'm just gonna do data based of rest metadata last update okay at example okay it's a it's a pretty stupid example but okay that's set and inside with over here we can save some data now not only if the data is always the same but we are not going to see it update so it's not going to be particularly interesting so right here I could just set the current time okay so I could do time dot day or whoa alright is date time Dino JavaScript oh it's date okay an example I can do VAR date equals new date and this is basically going to give us the the for today and I can do to date dot get date I think it's going to give me the timestamp probably hopefully and this is probably a function right yes oh no this gets me the date of the month okay so I don't want this again time is probably what I want yes get the time value in milliseconds this yeah this is exactly what I want and then as you saw from this function I'm actually gonna return in the world always just so the log so don't get filled with exceptions okay and I believe this is the last time I'm going to deploy and now before deploying make sure that you have enabled building on your project unfortunately scheduling functions can only work if your project is upgraded to the pay-as-you-go or blades plan you can actually have up to three free scheduling functions but in order to make it work because he requires the service pub/sub you need to have a billing account setup so i'm going to transfer these functions on a farm owner project which is on the blades firebase plan I'll be back in just a moment okay I've done that but one thing to note while the functions are deployed in order to actually start using the scheduling functions correctly you have to go to your project settings and then right here on your Google cloud platform resource locator you location you have to set a location after you set it you cannot change it later but as long as it's pretty close to where you are going to you know you're going to have most of your users it's not going to be a problem I actually tried out a bunch of different locations and I didn't have that much impact on performance so it doesn't really matter what you choose as long as you don't choose a database or a server which is in like Antarctica but I don't see any of those here so using any one of these two should be alright in my case I'm going to use the American one and I'm gonna hit done and now after you did this operation then you can deploy your functions without problems but even if you forget to do this it's just going to give you a log with telling you to do this so it's not a big deal alright so lastly here we are in the project which asked the blade's plan enabled as you can see and it's also called the multiplayer experience experiment which is also you know we could say a spoiler to my next video which I told you is going to be about these stuff but now in theory if we wait one minute this function should actually work hopefully positive I'm not sure actually we can actually go in functions and as you can see I have another function set up don't worry about this one doesn't seem like this one is working the one we we did ourselves as you can see is not working the reason for that is that maybe I messed up the syntax of the function I don't think you can actually use cycles I think you can go up to minutes so instead of doing every 60 seconds I have to go every one minute which is pretty strange but I believe I have to do this I thought I could use seconds but I guess I can't I guess calling a function every second would be way too overkill so that's probably why they didn't allow that okay and one last thing while it's deploying if you actually go to your Google cloud platform in your project and you go to cloud functions from here you can actually call the functions yourself so as you can see here we have our two functions the same that you saw on the firebase website and from here we can actually test the function so even if it's not time to call the function with this pattern you can you know call it remotely you know I'm saying this just in case you are calling a function once every year and then in order to test it you are just recently waiting for the year to pass when you can just click this button and it'll be what much quicker all right well now hopefully if we refresh this page the schedule ed function will work because it's going to show us that needs to execute yeah it executes every minute and if we go back to the database probably already I mean it has passed so probably already executed once yes it did so as you can see I have the time stamp right here alright so now we're just gonna you know I'm just going to do the outro and you're probably going to see this value update in just a moment okay thank you ever so much for watching this video to the very end and before leaving I think you can actually enjoy more content fire base if you are interested also I'm doing a series on machine learning right now it's kind of stuck because I'm working on this firebase stuff oh it just updated nice but yeah I'm working on this parable stuff that a lot of people are enjoyed for enjoying and are watching but yeah I will also be back with my series on machine learning soon and with that I hope you really enjoyed this video it was really amazing to make leave a like if you did and if you learned something new and I'm going to see you guys in next one see ya
Info
Channel: uNicoDev
Views: 23,389
Rating: undefined out of 5
Keywords: unity, game, gamemaking, tutorial, how to, firebase, firebase realtime database, firebase realtime, firebase database, realtime database, rules, security, secure rules, webdev, app development, typescript, javascript, lesson, database, data security, validation, json, data integrity, nosql, firebase emulator, firebase suite, cloud functions, cloud firestore, pubsub, firebase hosting, website hosting, emulator suite, functions, backend
Id: bpI3Bbhlcas
Channel Id: undefined
Length: 29min 24sec (1764 seconds)
Published: Wed May 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.