DC Flutter Jun, 2020: Firebase Cloud Functions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I Swan introduce myself and my co-host Larry my name is Barack soy I live in the DC area I have been in the past a technical manager and I've been in the android development space service I'd started my career on the networking side and recently I've been since the beginning 2007 I think September 2007 is when I found out about flutter up in a flutter enthusiast and they're following it keeping my hand on the pulse of flutter and dart ever since then recently about two years ago I've actually switched gears and I'm now in the cloud and in integration space I worked for Salesforce as a senior technical consultant doing integration but I always still keeping you know try to keep up with flutter and any kind of mobile development and I have with me my Coast Larry Larry would you like to introduce yourself I am my name is Larry Ellison and I'm acting as the moderator tonight so I'm trying to allow everybody in as quickly as I can thanks for joining this zoom session today I'm glad to have everyone here and glad to have our special guest Andrea with us today hope you enjoy the presentation oh so this will be recorded and it will be put on YouTube we will probably put the link of the recording to the meetup page at some point so without further ado I would like to give the floor to Andrea Andrea why don't you take it away introduce yourself and a great presentation from you oh thank you yeah thank you very much for the introduction and hi everyone welcome to my talk about five ways about functions I think the just a couple of announcements before we start I suppose if there's any glitches with audio and video let me know in the chat but other than that I'll be carrying on and as I said yeah thank you for taking the time to my talk today I'm happy that you've chosen to look at it I just noticed that today was the same day as Apple's WWDC so it's quite exciting that people are choosing to watch my talk is that but yeah I hope that I'll manage to keep you officially entertained and before I get to the main topic of the presentation I just wanted to say a couple of words about myself so I started using flutter and making tutorials for the community around a couple of years ago and as part of this I created a YouTube channel as well as a website where I share tutorials about Dart flutter and five ways and in these two years I've had the chance to use flutter in various client projects and also in a variety of demo apps that I made available with my tutorials so um today's talk is about crowd functions and the reason I chose this topic is that many developers are already using firebase as a back-end for the flutter apps and in this context I feel that cloud functions can really expand the scope of what you can do so in my experience flutter 5 ways and craft functions are a great way of doing full stack development so the way these talk is going to work is that I'll give you a brief introduction about all functions and then we'll look at the various types of cloud functions that you can create as well as a few code examples so that we can better understand when and how to use them in particular I will focus on background triggers and HTTP and Kalambo functions and to be fair crowd functions is a very broad topic so I can't really cover all of it in just one talk but I thought I'd just give you yeah a bit of an introduction and cover some of the things that I feel are interesting and and some of the bits that maybe are not covered so much on your documentation and also at the end of the talk I'll leave some references so that you can explore the topic a bit more in detail so yeah and we'll have questions at the end as well but I guess to start we can have a definition so what are crowd functions and a good a good one that I found a good definition of fun is that they are a way to write your own server less event-driven back-end so surveillance means that you can use them to deploy your back-end code without having to provision any servers and cloud functions have a few interesting properties they automatically scale based on the load like you would expect from a fabless product and they also have strong security built in and also some other useful capabilities in terms of pricing you only pay for what you use and this is based on the total execution time for all your functions and the bottom line I guess is that they offer a great development experience because you can focus on what matters which is writing your back-end code and before we go into more details I think the most important distinction that we need to be aware of is that there are two different products here one is Google crowd functions and the other one is called function for five ways so as I said there are two completely different products they have separate websites and entirely different sets of documentation so since we are most likely to bid flutter apps using five ways than the one that is relevant to us is called functions for five days but yeah just keep in mind this is part of a bigger platform which is the Google cloud function and so for the rest of this talk I'll be talking specifically about cloud functions for five ways and I guess the first concept that we need to understand is that cloud functions are triggered in response to events inside Google cloud services including any Fiveways products that you may be using so when you use crud functions your code runs on Google servers and that keeps your application logic centralized and safe so just to give you a few examples of things that you can do with five-way stop functions you could set up an authentication trigger to send a welcome email when a new user signs in or you for example receive an email or a slack notification when a new issue is discovered in crashlytics or generate a thumbnail when a user uploads an image to firebase storage you could moderate or remove any offensive words that are entered by a user inside your app or you can also do things like send FCL notifications to users and these are quite useful for example if you're building a chat application but you can also do things like indexing your files or database and implement full text search by tapping into external services like a Galia so I'll show you some code with examples later in this talk but before I get to that I think we need to talk about node so node is a runtime that allows you to write JavaScript code that runs on the server it was introduced in 2009 and he has become very popular because it allows developers to write full stack applications using a single language which is JavaScript so since crowd functions run on the node.js runtime we need to write crowd functions in JavaScript or a language that can be compiled to JavaScript so if you're writing crud functions for five ways the only languages that are officially supported or Java Script and typescript though I should mention that there is also an unofficial dart package that you can use to write crowd functions in Dart so you can find it on pop dev at this page and yeah if you're feeling adventurous you can give this a go but for the most part if you want to use official packages then you need to be using javascript or typescript so with out of the way we should maybe talk just briefly about setup so in order to write crowd functions you're gonna have to have note installed on your machine and you also need the Fiveways file which is a common line tool that you can use to manage and deploy your firebase projects so I won't be covering all the setup steps in this talk and I'll leave some more links at the end so that you have everything that you need but for now I think I'm just gonna show you a quick hello world demo and that is a good way to show you how you create a simple project and also how kind of faith things fit together [Music] alright okay oh good so yeah so over here I have a firebase project that I created from scratch it's got pretty much nothing in it it's just an empty project called hello world so you could create this from the firebase console if you wanted so what we want to be able to do is to configure this so that we can write some crud functions for it so here I just have a terminal prompt and here for example I could create a new folder and call it hello world and I can see B into it and then once I have the five ways client I can type five ways in it and this will configure the project with five ways this is an interactive prompt that is going to ask us a few questions so the first one is to choose which features of five ways we want to use so since this is just a simple hello world application I'm just going to choose functions then we have an option to use an existing project or create a new one so if you have already created the project like I've done in this case you can go here and find it over here and then you get to choose which language you want to use I think typescript is better for a number of reasons reasons in terms of type safety and other features that it has so up until now I've been writing micron functions with typescript and then we can also enable the eslint which will help us catch additional potential bugs in our code and then the last step is to install the end the dependencies with at the M and the M is the equivalent of pub if you're using dart so that's what you used to install dependencies in JavaScript land so once this is complete I can open up visual studio code instance on the project that I just created and the next thing that I think it's good to look at is the project structure so when you create a file based project this way you're gonna have a few selected class functions you're gonna have a functions folder and the most interesting file maybe that you want to look at initially is this one so it's called package.json and this is the equivalent of your pub spec demo file so so this is where you would install your dependencies so there are a couple that empty Emma's already installed for us which are five ways admin and functions and we will look at this a little bit more in detail and in general what you would have to do if you wanted to install new things would be to go here and type NPM install and then you choose one of the packages that are available from NPM once you do this then the package will appear here and it will also be installed inside this folder which is called node modules this is a folder that contains a ton of dependencies but you don't have to manage this yourself NPM does it for you so this is something that you don't want to modify and typically you want to add it to your get ignore file so that's the package.json along with that we can take a look at the source folder which is where your main application file lives by the way before that I should also point out that there's this section called engines and he says note 8 which is what is created by the standard templates if you create called function projects make sure that this is set to 10 because not version 8 is getting deprecated so just one little tip to know that there's this main key here which points to little indexed ojs which is what our application but what our trial functions will compile to but since we are writing typescript the main entry point for us is under source and it's called index dot TS and this is just your standard hello world application so how does this work it looks like this by default so at the top we are importing the file based functions model and then we make it available as a functions identifier so that we can use it here in our code and then the first thing we do is we export a function called hello world this is defined as an HTTP pipe function that responds to a web request so this gives us a request and a response parameter and these are object types they come from expressed ojs which is a web framework that you can use to for example to write rest api s-- and then all we do in their response in the body is to just send this string back to the client with response dot send so the bottom line is that this function responds to all incoming HTTP requests by sending always the same cont response with this comment once you had this what you can do is to the fly it so you can go into your functions folder and then you just type in five days deploy yeah and this will yeah just compile all the code from typescript into in this case into JavaScript and then once that's done it will yeah just deploy the function onto five days and when it's finished it will give you a URL that you can use to point your browser to to get access to the function this may take a few seconds so I'm just going to skip this because I've already kind of done it beforehand but once the function is deployed if you go on the function stop in five days you're going to be able to see it here so what you can do is take this URL you can copy it then if you want a new browser tab you can enter this and if my wife is happy yeah so yeah it just runs and prints back the response that we set on the client okay so this is kind of the super basic example the earth I was at least useful to cover for the ones of you who might never use cross functions before but I think we can look into something a bit more interesting now so we managed to deploy our first cloud function but just one second yeah so we have just managed to implement on HTTP trigger which is something that can be called directly by the client by making a REST API call to the cloud function URL but there are also other types of background triggers and these are different in that they are not called directly by the client application but instead they trigger they are figured when something happens so we could probably divide crowd functions in two groups background functions and cloud functions that are called directory so within this second group we have standup HTTP requests as well as caller blog cloud functions we'll take a look at the difference between HTTP and color ball a little bit later but the general idea is that the client calls the cloud function directly and this in turn could access some data in file store do some computations and send our response back to the client on the other hand background triggers are maybe more common and yeah for example a very common flow here is when a client up writes something to file store and this triggers a crowd function that updates some data according to some server-side logic so this crowd function could then write back to file store and then the client app can listen to changes in real-time so in this scenario the client app only talks to file store and doesn't care or doesn't even know about cloud functions running in the background so to give you an example of background triggers I prepare another demo so let's take a look at the code and in fact before I show you the code I should show you what it is so the demo is our restaurant application where what you want to do is to be able to rate restaurants and by doing that we're gonna have some cloud functions that will calculate for example the average rating for a restaurant so this is something that is useful in a lot of different apps you can use it as I said for restaurants you can use it for things like say you have a movie database you want to rate movies or books or online courses anywhere where you might want to do in operating so yeah the idea here is that in five days in five store I have a top-level collection called restaurants and inside it I have a number of restaurants and each one of them has a name and optionally this rating and the number of ratings so the idea is that users can see the list of restaurants this is obviously a very bare-bones application you would probably have a lot more content in it and more details about the restaurant and whatnot but just for the sake of doing the in operating the idea is that you can see the list and then for example you can drill down into a detail screen and what you do here for example is to rate a restaurant for example and changing the rating and what happens when I do this is that I'm actually writing the rating into a sub collection for the restaurants document and I'm using the currently logged in user to reference the rating and what happens is that when any of the documents inside this collection changes then a crowd function is triggered and that will recalculate the average rating and the number of ratings so this is not something that we can or should do on the client because clients should only have read-only access to the restaurant data in this case and the only thing that they're asked that that the client can write is rating value for a for assigned a user and instead the logic for calculating the average rating should live on the server so this is a good example of how we might do this with a crowd function and if I show you the code for this over here I have the same function the same package folder structure that I will show you before but this time inside my index TS I export a function called update restaurant reading this is triggered when there is a bright event to a 5-star document that matches this specific part and and just to be clear when we define a 5-story ger we can choose between on create on update on bolete and on bright and on create will only be triggered when the document is first created whereas on update is only triggered when the document is updated so in this scenario I want my users to create a reading as well as updated later on so to catch both on create and on update I can use on bright and this will give me a change object this object is something that I can use to see the contents of the document snapshot before and after the change so what I'm doing here is to call this internal update ready function that I created and then and then what I'm doing is to get a reference to the restaurants ratings collection which is which would be the parent of the rating that I've just changed from the client and then what I'm going to do here is to list all the documents and then just do a loop where I can go through all the documents and I can yeah essentially just calculate the total and the average rating as well as the number of ratings across all documents and then after I'm done with this what I need to do is to get the reference to the original restaurant document and this is the one that you kind of see over here which has these properties right so once I had this I can call an update method and I can pass along the new values that I've just calculated so this is how you would implement the crud function for this and and once again I could show you like our run time how this works so I can go on to a different restaurant and here I could for example change the rating and submit it and you can see that it kind of took maybe a second of to update and the reason for that and this is something that is worth being aware of is that when crowd functions are not used often they go through a cold start so this means that because crowd functions are stateless sometimes the whole environment needs to be set up so that a cloud function can run so when crowd functions are called infrequently you're more likely to get cold starts and so the execution time can take longer but on the other hand if you have a live up with a lot of users then your whole function may become more frequently and in that case you will experience fewer cold starts so this is just something to be aware of but in any case I can go back to the code and one thing that I can point out is that this function that I created is asynchronous and in fact I have a number of await calls inside the function body and this is the same pattern that you use in dart when you do a wait I don't think but the important thing to remember here is that yeah trial functions work with promises which is again in the art would be a future but it's the same concept and and we should keep that in mind and the other thing that we should keep in mind is that we should AB we should only ever return from a cloud function well when all the internal of synchronous calls have completed and that's because when a koala function returns it can be shut down by the server instance that is running it so by awaiting on all these synchronous operations we make sure that we really complete all the tasks that we need to do before we we exit the cloud function the other thing that I want to point out is talking about the firebase admin SDK as you can see at the top here I'm importing this Fiveways admin module which I'm kind of referencing as admin and the first thing that I do here is to call admin dot initialize up and this is something that you need to do in order to set up firebase with all the correct settings for your project so in this example and you can do other things with the admin SDK as well so in this example we have made changes to some collections and documents just by going through the references that we retrieved from the change object but if you use the admin SDK you can actually access any collection or document that you want with the syntax that is a bit like this so you could just call admins of five store dot for example document and then a specific path to get access to that document and this when you do this you get full read and write access to that document so the very important thing that you need to know is that file store rules don't apply when you use the file the admin SDK and this makes sense because call functions run in a secure environment and is that if you run code on the client you had to adhere to the feistel rules so that's again something else that you need to be aware of and there's a difference there between the admin SDK and the client SDK okay so we have seen now how background triggers work and then I'm just going to go back to the presentation that we just covered and yeah so the other thing that I want to talk about is to just get back to the HTTP triggers so that we can see how to use them and when they might be useful and so as just as a reminder HTTP triggers is what we use when our client needs to call a crowd function directly and this yeah as I said this could call into file store do some logic and and return the response back to the client so when exactly would we want to do something like this and there's a few examples one of them for example is if you want to join data from multiple file 5 store documents and it is too complex to do this on the client then it might be better to do this we call functions another reason might be that the security rules that we would have to set up are too convoluted to be done on the client so again that's another use case for an HTTP function other reasons is that we simply might not want the data to be accessible to the client and it's just safer to process everything server-side before returning a response an example of this would be for example coupon validation so let's say that you have a coupon system where users can try to redeem coupons and we want to be able to validate coupons only on the server before they can be used so all this logic is much safer on the server and the client all the client needs to do is to call a crowd function to violate a coupon and check the result that comes back so if you find yourself in any of these use cases then on HTTP or a collabo function is the way forward and and in fact maybe I should this is now a good time to talk about the difference between HTTP and callable functions so first of all the syntax is different up until now we have seen on request which is how you create an HTTP function if you want to create a callable function you have to right uncle so what are the differences HTTP functions are good for example if you want to implement our REST API it and and if you go for this approach it means that on your flutter up you can use the for example the dart HTTP packets to make a standard request and then get a response and parse the JSON data on the server side you will get request and response objects so you can use Express not js2 yeah just for example read the data from the request and also send the data out with the response it is hard it is tedious to do a lot of things with HTTP crowd functions because we will see this but yeah they involve a lot more work on the client and on the server as well to do things like authentication and in general they they tend to result in a lot more boilerplate code so the way this is solved with callable functions is that we have a client SDK so the client just uses the SDK which does a lot of the heavy lifting for us so this makes it a lot easier to work on the client if we use callable functions on the server side they give us a context object which again has a lot of the useful things that we might want to check including the authentication data so that makes authentication authenticated requests a lot easier and the bottom line really is that whenever you can 99% of the time you're better off going with colorful functions and I think just to maybe show you in practice how this works I'm gonna show you another demo so what I have here is a different map I'm just gonna actually show you the database first and also the client so the way this works is that it's a very simple top tips up so the way it works is that over here on the database I have a number of tips about best practices in flutter just to make a simple example and what happens is that here I have two buttons on the flutter up and when I tap on any of them now he's going through a cold start so you see that it's actually taking a bit of time but what it does is call the cloud function this in turn will choose a one of these tips at random and they will return the response back to the client and the same goes for the collab will function they do the same thing so what we're going to do now is to look at the differences in how these are implemented with HTTP and collarbone functions so if I open the project again here we're gonna have an index dot TS file at the top we're going to initialize the admin SDK we have some authentication logic which I'm going to show you a little bit later for now I just want to focus on how we satisfy the request so at the top we have a cloud function called get random tip using rest this is an HTTP request call function which takes requests and response arguments and what we do here is to call this common function that I called get random tip and this second function is very similar but this time is a callable function and the arguments are different because we get a data argument and a context but the bottom line is that both of them call the same thing so if I open this this is actually really simple it's just to show you the difference so what it does is to get old it but get the collection of tips from faster and then I just select our random index I pull the document for that index inside the collection and then I returned this back to the color so the difference here though is that when I implement this using the HTTP function to turn and response back to the client I need to say response not send with the resulting data whereas with a callable function this is actually a lot simpler all I have to do is just to return the data at the end so this is how things look on the client side and and now that I show you this I think I can show you the client as well so let's see how this might be implemented but we will have a main file inside here I have this home page which is the one that you see over here it's really simple I'm just doing here bare-bones code that you will need just to to prove the concept so these two buttons are actually implemented inside these API buttons we just closed and they're just yeah two raised buttons inside the column so the interesting bit is that when you press the buttons and we hit the the bottom code box this is where we make the requests the cloud functions so in this case with the REST API service I have a provider that I've instantiated at the top of the widget tree and this gives me access to this REST API service I'm getting an access token and I will talk about this a little bit later and then what I do is called this method inside the REST API service and as I was saying before this is something that uses the dart HTTP package so what I'm doing when I call this method is to get the URL that I need in order to call the crowd function and then I can make an HTTP request passing the URL and then I need to pass some headers once this request is complete I get a response and typically what I want to do is just to check if the status code is 200 which means everything is OK and I can just decode the JSON body and I return a top tip which is a data model class in this case and this is also where you would any exception handling code so this kind of works but there are some things that are not so nice about it if I scroll up a bit what you will find is the for example you need to explicitly set the base URL that points to the cloud function URL and this is not great and it's actually even worse if you have multiple flavors in the app and you want to connect to different file based instances depending on whether you're running on that staging or production then you're gonna have to do this kind of switching logic and just so that way you can get the base URL for the for the correct environment so this is a lot of boilerplate code and it's kind of repetitive to have to do this on the other hand I can show you what the crowd functions version of it works if we use callable functions and this is a lot simpler at the top we just import cloud functions dart which is a package one of the five base packages for this and then it's actually a lot simpler all we have to do is to get the name of the function that we want to call so in this case this is how it's called in the cloud functions folder as you can see like here we don't really need to worry about URLs and environments none of that stuff because the the kernel functions SDK does all of that for us so it's a lot easier to manage if we wanted to passing some arguments that our back-end code will process we can pass them here as a map but the essence of it is just it's just that we call this we don't know synchronous code we can get the result and we can parse it just in the same way as we did before so yeah this is a lot simpler just quickly if I show you the pub spec no Yama file for this project if if you opt for the REST API solution you could use HTTP or another dot package that you might want to choose for networking and if you want to use colorful functions you just need to import cloud functions in the fashion so I guess the bottom line is that we can save a lot of code by using colorable functions but there is more as well because when I will showing you the REST API suit up over here I was getting this token and this is something that in turn is passed on to the authorization header so this is actually how you do kind of authenticated requests traditionally with rest at the eyes you just get a token and you can pass it on like this in order to enable this you need even more boilerplate code because you have to get the current user from five days old again this is not code for production I'm just showing you the idea but yeah you need to get the user then you get token from it and then you return this object and then you have to pass it down to the REST API so it is a lot of extra steps that you need to do and it is a lot of extra steps not just on the client but on the server as well this code that I previously commented kind of goes like this so if you pass the authentication bearer from a client this will come through into your request object and what you have to do if you want to authenticate the requests is to parse this and you kinda have to write all of this stuff manually so this is just code for extracting the correct token from the authorization headers yeah it's just quite a bit of extra boilerplate code once you have the token you can then call this function on the unpin SDK to verify the token and from here you get a decoded token which is what you might use to get the user ID so again this is quite a lot of stuff on the other hand if you use the color ball version of it it is a lot simpler like all you have to do to check if the user is authenticated is just one if statement and if you don't have a note object inside your context all you have to do is just to throw an HTTP error and then you can catch this on the client so again authenticate is a lot simpler and just to show you that we practice out these works I can actually log out of this application and this takes me to another sign-in screen where I have the same buttons but this time I'm not an Authenticator user so if I try to call this now I get 401 status code for the REST API and I also get an error on the cloud function so that's how you do all tent occation it's actually okay so let me just go back to those lines so yeah up until now we have seen three different examples hello world just to start with we have seen how to implement our restaurant rating system using a background trigger and we have also seen some random fluttered tips random rotor tips up both with HTTP and callable functions but what else can you do with cloud functions and yeah the answer is that you can do really a lot of things and for this I think there is a great resource that I've been using a lot when I was learning about cloud functions this is a collection of samples from the firebase team and they just cover probably 90% of the kind of things that you would want to do across functions it starts with some simple kind of things just just to get the idea of how this works and then there are some more complex examples as well so and this will show you how to do things like sending FCM notifications charging customers with stripe or PayPal it will do things like food texture to the gaudiya which is what I was mentioning I was actually planning to cover this in my talk but I don't think in the end it didn't quite fit so but you can find the code for this on this repo directory and so yeah definitely this is a very good resource to have what other things are interesting there are maybe some best practices which I'm not going to cover in a huge amount of detail but maybe as we close up just a couple of things to be aware of one thing is that as you start building malfunctions you typically have all your code in index dot TS but as your color functions folder grows you don't want to have everything on one file so what you can do is to start moving some of the internal functions into separate files and then you mark these functions with export in the file that you want to import and then inside index dot TS you just use this import syntax to get a reference to the function that you want to call and then you call it like that so yeah I think the idea here is that imports and exports give you a way of splitting up the code so that you don't have everything in one file the other I guess important thing it's worth mentioning is that with called functions because they can be used concurrently it's a good idea to use transactions if you have multiple reads and writes so this is something that you can do with the crime with a client SDK as well so if you use file store in the earth you can write code with transactions but you can do the same server-side and it's perhaps even more important to do a server-side because you can get a lot of concurrent requests from a lot of different devices so it's important to try to keep your database in a consistent State and the way to do that is these transactions I might even show you a very quick as a quick example of this in code this is another project that I've been working on just to show you how you use transactions the idea is that you get your five storm object from the admin SDK and then you call run transaction this will give you an a synchronous function body and so in inside here rather than creating or updating or reading documents in the way you would do before you always do it through the transaction object that is an argument to this function and then you just call all your metal like this all your metals like this and the good thing about it is that the transaction is atomic and that means that you're all your call other because either all succeed or all fail so that ensures that your database in a consistent state so yeah I think this is one thing that is worth keeping in mind you can don't really need this if you if you have to do multiple things like this and yeah I mean there are still many more tips that I don't actually have time to cover fully in this talk but [Music] yeah I think there are many more things that I haven't really covered if you visit this URL this is the source code for the restaurant I think I started writing up the table showing you earlier so here you'll find the source code for this but you'll also find a whole bunch of links with kind of some material that you might find useful if you want to learn a bit more about crowd functions so yeah I hope that this would be useful and other than that I think we reached the end of my talk so thank you very much it's time for questions I can see that the chatters filled up already quite considerably that's that was great great presentation if you want I could read out some of the questions and let's see if we can have you some of those you can just want to start it let us see how I can answer it okay so it says what happens if more than two persons update the rating concurrently if two people hit the rating core currently in terms of the right that the client does because they will be two separate users they will write two different rating values into two separate sub document but once the I guess the cloud function will be triggered twice so you would get a first trigger and that's where you know that's that's let me actually look at the code my understanding is I think what he's asking is more of a generic questions what if two people what if there's a Racing Commission in other words there's two people updating the same record how about that what happens that last one wheels right last one would win yeah I think the it's a good one if you use your code I guess with transactions you are at least guaranteed you know the first update comes in and it's executed and then the second update only starts once the first one is fully completed so I guess an example where you might see this kind of scenario is say for example on Twitter you have the number of likes for a given user so say you have a hundred likes and another user comes in and does an additional one and then another user does one more you will get probably a trigger on the first one which will read the current value which is a hundred and that will update it to a hundred and one and if you do this with transactions you're guaranteed that the second trigger would have to read the updated value because it would only I guess enter that document with the value 101 but I think there are additional considerations I mean this actually works on a scale where all the data is kept just in a single location so if you normally have just one database instance where this that I stored so that's how it works if you talk about networks like Twitter or Facebook where they have like millions of records it's likely that their data is also divided into separate locations so I'm not too sure exactly how they implement that kind of behavior but at least if the data is just in one place with malfunctions you kind of need to do it with transactions and at least you can guarantee that you're gonna do read and write for the first trigger and they'll read them right for the second trigger and that way you keep them in sequence so they ask you to your question J Rama will be if you find that you're gonna have a situation where there is some kind of a racing condition you make sure that you write transactional code so there's not the question says it seems like it would be easy to accidentally write infinite loops if you modify a ref a reference in the on write listener that's - what to do to safeguard against that yeah that's correct so in this scenario that I've shown it doesn't apply because we read from one location and we write to another one but one scenario where this applies is for example if you're doing text moderation so say that you're leaving our rating for restaurant you might want to replace all swear words so if you say coca-cola it's a swear word and you want to replace it with Pepsi you can do that and because you will be updating the same document that would trigger an additional update so you had to be defensive in your coding and when you implement the cloud function you had to basically check if the basically you would have your your text inside the document that is the one that you want to change what you can do is to check if the modified text is going to be different from the one that you already have so it's a case of just adding a condition on inside your cloud function and make sure that you exit the loop so you and what you want to avoid is to write again to the same document location if the text didn't change and that gets you all to the loop in my work in that scenario in a generic sense I guess you you just have to write defensive defensive code you just have to write defensive code it's a it's a little bit like when you have recursion like you're writing a recursive algorithm you want to have a condition in there that gets you out to the exact so that goes back to basics of writing good good good code I guess right so I have a different a kill rises I have different fibrous environments for development staging and production my folder project since cloud functions are created by a fire plate firebase CLI how do I go about deploying cloud functions to these different environments when building what CI yeah so what you do is this you try firebase use which is a comment shows you different aliases so when you first configure your project you would point to a specific firebase instance so for example development if later on you add a new project which is your staging or production environment you can do five ways you'd and then add I think it's called and that gives you a way to select one more project inside your firebase console and and then associate an alias to that so yeah you can basically have multiple projects that are active and configured in your in your project and then you can switch between them so when you deploy you can say five ways deploy minus P and then you specify the name of the alias and that's how you choose which firebase instance you want to deploy to so Boris asks I don't is more more of a question outside of what we covered today but if you have any just quick tip I usually don't write flawless quote in first John what are your best practice for debugging remotely locally emulator that kind of stuff yeah it's a good one so crowd functions for the ones that may not be aware what I cover so far is like how you write it and how you deployed and once you have deployed it there is a way that you can check what's going on and that is by going into so you have a log stop and this is where you can see everything that is happening so all the functions are being triggered or the errors all the functions that are being deployed and this is where you see the logs this is useful for monitoring in production but when you're debugging locally you don't really want to have that developer loop where you deploy and then check the logs and go back to the code it's very very slow so what you can do instead is to start up an emulator so what you saw with the emulator you can just call functions there is basically like a ripple mode as well so you can enter like an NPM interactive mode and and what that lets you do is to have like an NPM shell and with that you can call functions directly if you're running them on the emulator and pass arguments directly to them that works if you want to kind of do common line type of stuff it gets more complicated if you're I guess trying to debug an app that may be running on the simulator already because the app is configured to to point to the firebase instance where the code is already deployed so I don't think I have an answer for that but if you if you just want to do things locally there are some good use cases for this for example sometimes you want to do things like database maintenance and you want to check if say for example you are introducing new types of fields to your file schema with a new version of the app and you want to upgrade all use all old users to the new schema you can write a function that will do all the update going through all the collections and documents and if you're just testing the functionality you can start up a local emulator which lets you run functions locally on your machine the caveat is that you can then choose to either also have a local database but you can have your local functions talking to the to the database on the cloud if you want to do that there's a thing that you need to do that lives in the project settings there is a thing called service accounts and that is what so what that lets you do is to create a private key that you can download then you can point a certain environment variable to that key and that lets you use local functions to talk to the remote database and there's some security considerations behind why you need to do it this way I'm not sure if the links I shared already include I think yeah is here like manage function deployment runtime options and environment configuration nice ok great so I we're running over just a few minutes I'm just gonna see if we could maybe answer is whatever is left or maybe at least one or two so the lotty Pavano asks one important thing you missed is the use of firebase JSON to specify rewrites yeah so that your endpoints have different string than the name of your function I guess it was probably hard to cover everything you have I think it's C member now I think there is yeah so if you don't want to call directly the URL that comes out of 5 ways which is the function URL you can set up re-write and that helps you especially if you are going to be calling these functions from the browser because there's a thing called cross region reference I forgot now what the economy is like but I tell you actually the best well I did write about it like recently so this is one of my recent tutorials where I cover yeah I'm doing cross origin resource sharing and how that works and what you have to get around the problem if you are hosting your firebase project with with firebase hosting okay great so Martin's prologue asks any dart2js shortcuts excuse me to create a cloud function code from dart file I don't know I haven't really looked into that kind of thing like the the closest I got to club functions and doing stuff with dart was that the plugin that I was mentioning so I don't know if that one lets you do what you're asking for that's as far as I got on that one sorry yeah that's fine um so Gaurav wore masks I've recently used MongoDB realm this is quite similar to the web hook available there can we expect support for MongoDB Atlas at any time in your future so I guess is the question around being able to have cloud functions talk to MongoDB or having some kind of crowd function triggers for MongoDB I'm not sure I've never used one thing I would say is crowd functions because they're built on top of the MPL microsystem you can install any package that is available with NPM so if there was an SDK they give you access to MongoDB maybe with some I don't know web sockets or whatnot then you could as long as you can import that dependency into your crowd functions project and then you can call into those metals but that's as far as I know like I don't know how in practice you would go about setting up trigger triggers triggers are tied into five ways in a way and I suspect anything outside the five baseboard it's more a case of importing libraries and calling maybe your STP I typed kind of function ID or maybe using WebSockets okay and the last question and I'm not sure if I understand this but maybe you will thanks a lot Andre it seems firebase cloud functions can completely replace the REST API is that right I don't think so but anyway even if I have a website version because there are apples and oranges right I mean I think there's anyway even if I have a website version of my mobile app I still can call these cloud functions right yes you can because the code function Client SDK is available in most languages so you can I mean there's a version of it it's certainly available on web in fact when you create a flatter web project you need to import the Java Script equivalent of the cloud functions SDK and then you can call it in in the same way so the only reason why I would prefer using the REST API is if you're building a service for someone else and in that case you are make your basically building your own REST API for someone else to consume but if you own your back-end and you're building enough for yourself then you're I mean you have full control and there's no reason to go through all of that you you just use the cloud functions SDK and it's it's a lot simpler okay that brings us to the end of the presentation and luckily one of thanks users great presentation Andre thank you so much I've been using cloud functions since for a long time I learned something today for me about callable functions I guess he wasn't using that Andre thank you so much is there anything else you'd like to add Larry or we're happening an upgrade no I don't think so um that was that was very very good I actually learned a lot myself and I wish I could have taken some notes but to go back and watch the video like again there's a video yeah we will be publishing this so we'll make an announcement on the meetup page right Larry with with the link to the video so the yes will be posted on YouTube and put a link up on that page yeah and this saundra is a prolific publisher of I mean I've I've been following your material for a while now Andrea you know just big thumbs up kudos everything you do is not much under percent in today's presentation was great we learned a lot I think and we we went a little bit outside of the regular you know flutter discussions is something more useful and real tangible that's the real world I think that's why I wanted to give this talk because you know one thing about myself is that I've been like a front-end developer for like eight years and I've never never touched any back-end code like in the last until the last six months and then I thought okay I know five days now I I started a project a few months ago where we had to do some functional stuff and I started looking into it and I don't think there's anything magical about it like it's again a library that is actually very well documented the firebase team are some really good videos about it there's courses from other instructors that are really good so there's already a lot of really good learning material there and it's just a case of exploring it and trying it for yourself like you would do if you if you're just learning flatter right so and and the good thing about it is that once you know it you can actually do full stack development and that's quite empowering that's quite cool so that I think why I wanted to talk about it yeah and I like that functions - samples the website that's published by the firebase team that's some use cases but you shared earlier yes so but yeah so thanks a lot Andrea I really appreciate it we all appreciate it there's a great presentation and so I guess people want to get in touch with you or consume your materials code with Andrea right that's the website you can find me on Twitter but yeah I think if you go my website then all the links exactly okay everyone thank you for joining and we look forward to seeing you all next time thanks everyone good
Info
Channel: Dev Community
Views: 4,443
Rating: undefined out of 5
Keywords: flutter, dart, firebase
Id: 9oI4gu91PHA
Channel Id: undefined
Length: 63min 58sec (3838 seconds)
Published: Tue Jun 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.