We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Hacking real time messaging with Firebase

00:00

Formale Metadaten

Titel
Hacking real time messaging with Firebase
Serientitel
Anzahl der Teile
61
Autor
Lizenz
CC-Namensnennung 3.0 Deutschland:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen.
Identifikatoren
Herausgeber
Erscheinungsjahr
Sprache

Inhaltliche Metadaten

Fachgebiet
Genre
Abstract
In a serverless world Firebase can fulfill a promise of providing your app with realtime notifications. Firebase can be a great shortcut when you want to have real time notifications between your client apps by leveraging the observable streams Firebase provides in your React components. After the talk building a real time notification system will be simpler to maintain and come with scalability built in. I will try to leverage the real-time Firebase database for building a subscriber component for my application so that I get notifications as they are available. 1. How would I normally do real time notifications: Using redis with PUB/SUB and websockets to subscribe to publish and consume data 2. What is Firebase: Firebase is a real time datbase that takes over some of the complexity of managing your data. It has many language wrappers and is very easy to use 3. Wrapping Firebase library in a react component: In order to preserve the one way directional flow in React you need to wrap your firebase library inside a component to take advantage of the lifecycle 4. How Firebase and React work with the Redux state management: Once the firebase library is wrapped you can map the properties and dispatch actions when new data is available via Redux 5. Putting it all together: This is a wrap up and lets you know how all the pieces fit together 6. Live Demo: We will have a component that does a very basic insert into a firebase bucket, and updates the firebase letting the other users know that new data is available, followed by a live demo of the app
DigitalsignalLokales MinimumSoftwareentwicklerMessage-PassingComputervirusEchtzeitsystemTwitter <Softwareplattform>Computeranimation
Virtual Home EnvironmentHackerSoftwareentwicklerBayes-NetzPrinzip der gleichmäßigen BeschränktheitWiederkehrender ZustandBitProdukt <Mathematik>ProgrammfehlerGamecontrollerLastZentrische StreckungSoftwareentwicklerFigurierte ZahlZentralisatorOpen SourceGüte der AnpassungLastteilungPrototypingCASE <Informatik>Rechter WinkelKartesische KoordinatenApp <Programm>Physikalisches SystemCodeProjektive EbeneServerCLIMultiplikationsoperatorSoftwarewartungAnalytische FortsetzungComputeranimationXML
Funktion <Mathematik>PunktwolkeCodeHackerQuaderWarteschlangeKomponententestFreewareDateiverwaltungCDN-NetzwerkHumanoider RoboterArithmetisches MittelVerkehrsinformationFramework <Informatik>SoftwaretestVarietät <Mathematik>Formale SpracheSystemzusammenbruchProgrammbibliothekEchtzeitsystemCASE <Informatik>GoogolDatenbankZentrische StreckungMulti-Tier-ArchitekturInformationsspeicherungFunktionalPunktwolkeAuthentifikationWrapper <Programmierung>SichtenkonzeptMultiplikationsoperatorComputeranimation
HackerApp <Programm>DatenbankCodeDatenverwaltungProjektive EbeneAuthentifikationAggregatzustandDefaultAutorisierungE-MailHumanoider RoboterPasswortBenutzerbeteiligungKonfiguration <Informatik>Ein-AusgabeSpielkonsoleKonfigurationsraumProgrammbibliothekSoftwareentwicklerBildschirmmaskeBitPunktFramework <Informatik>UmwandlungsenthalpieAuswahlaxiomDebuggingMessage-PassingWarteschlangeGarbentheorieEchtzeitsystemComputeranimation
KonstanteKartesische KoordinatenWeb-ApplikationÄquivalenzklasseGamecontrollerElektronische PublikationInteraktives FernsehenHoaxZahlenbereichFront-End <Software>DatenbankFunktionalTouchscreenPasswortSchlüsselverwaltungCodeKonstanteObjekt <Kategorie>BenutzerbeteiligungSpeicherabzugEigentliche AbbildungSchlussregelComputeranimation
ZeichenketteWurm <Informatik>SchlüsselverwaltungKonstanteHackerInformationsspeicherungPasswortZahlenbereichKartesische KoordinatenEreignishorizontRoutingInformationsspeicherungKette <Mathematik>App <Programm>Produkt <Mathematik>SchlussregelTextbausteinObjekt <Kategorie>Domain <Netzwerk>ProgrammbibliothekKonfigurationsraumDatenbankEindeutigkeitProjektive EbeneAutorisierungAuthentifikationRechter WinkelSpeicherabzugComputeranimation
SchnittmengeVerzeichnisdienstSichtenkonzeptKomponente <Software>ClientModul <Datentyp>AppletTopologieGEDCOMTypentheorieTurm <Mathematik>DateisystemGruppenoperationSoundverarbeitungDefaultTypentheorieMatchingRefactoringOrdnungsreduktionInformationsspeicherungKartesische KoordinatenWurzel <Mathematik>MultiplikationsoperatorGamecontrollerKonfigurationsraumGüte der AnpassungProzess <Informatik>PunktZusammenhängender GraphObjekt <Kategorie>Token-RingFunktionalRoutingTeilbarkeitEinsDatenstrukturDebuggingAuthentifikationAutorisierungAggregatzustandBitZeichenketteMailing-ListeCASE <Informatik>DigitalisierungWeg <Topologie>GruppenoperationZahlenbereichFehlermeldungDatenbankValiditätDemo <Programm>DifferenteDickeRenderingGeradeMathematikFormale SpracheElektronische PublikationVariableWasserdampftafelSoftwaretestAutomatische IndexierungHydrostatikKlasse <Mathematik>Message-PassingBildschirmmaskeFormation <Mathematik>TemplateComputeranimation
SichtenkonzeptProjektive EbeneGruppenoperationAggregatzustandOrdnungsreduktionInformationsspeicherungKartesische KoordinatenRechter WinkelRechenschieberComputeranimation
GruppenoperationBitMathematikEreignishorizontEchtzeitsystemComputeranimation
ProgrammbibliothekMathematikObjekt <Kategorie>RechenschieberPunktEreignishorizontDatenbankTypentheorieFunktionalGruppenoperationElektronischer ProgrammführerSystemprogramm
GammafunktionGruppenoperationServerMathematikEreignishorizontApp <Programm>NP-hartes ProblemInnerer PunktWurzel <Mathematik>Demo <Programm>Computeranimation
HackerVorzeichen <Mathematik>URLTonnelierter RaumQR-CodeBitRechenschieberVerzerrungstensorMultiplikationsoperatorMereologieVerschlingungNotebook-ComputerDemo <Programm>URLCodeComputeranimation
SchnelltasteTwitter <Softwareplattform>CodeFreewareMulti-Tier-ArchitekturKonfigurationsraumDemo <Programm>Computeranimation
Transkript: Englisch(automatisch erzeugt)
He's a full-stack developer. He started out with Python, and then went over to the dark side. He just told me, and he's going to talk to us about real-time messaging with Firebase. Hello. Like I said, Artur, and I'm going
to help you, hopefully teach you to leverage Firebase for doing real-time messaging and notifications. You can find me on Twitter, and I'm a full-stack developer for a health care startup in London. And I get to work with a bunch of stuff every day,
React Native, React, a bit of IoT, so all the cool new things. But yeah, pretty much nice technologies. And I do enjoy it. I do enjoy writing code. I do enjoy solving problems. I do enjoy playing with new technologies.
And of course, I do want my everything to scale to one zillion users. I wanted my product to be loved by everyone. And at the same time, I want to be in control of it all. So I want to be able to solve any problems, know everything that's going on everywhere in my application.
And that brings me to one of my guilty pleasures, which is overengineering. In case you guys don't know, overengineering is something like building a bike that does a zillion other things other than being writable. So for example, in this picture, you're going to have a bad bike on the right.
And well, depending on how you look at it, good bike, bad bike. Anyway, let's begin. So I started looking into the real-time notifications. And I immediately thought Redis could help me with this.
Because Redis is open source. It has a lot of features. And it also has Redis CLI to help you prototype and figure out what's going on with the messaging inside the PubSub channels. But for this thing, you need the DevOps. Because after a while, you want
to get it custom and all the advanced features. And then you need an app server, a front-end application, a load balancer. Because we do want to scale, of course. Centralized logging, because if you have a bunch of nodes
and already you have two servers, which is one of the load balancer, one is the Redis server, you're going to want to centralize those logs. And then stats, because log data is massive and you won't be able to parse it quickly enough. And then after a while, you get to have a system that takes up three of your developers
and looks kind of like this. And you're dead center of it. But this is just a feature. And usually, when you work on a project, you're going to have not one feature, but many.
And at the same time, you're going to have to develop the other features. You're going to have to maintain continuous delivery. You're going to have to do bug fixing, keep your customers happy. So yeah, it's going to look like changing wheels on a moving car. And of course, we're all familiar with this guy. And hopefully, it's sometime in the future.
But most of the times, it's yesterday. So here is how Firebase can help us. It provides a wide variety of features. You get the real-time database, of course. You have the crash reporting. You have Cloud Firestore. You have authentication. You have Cloud Functions, similar to AWS Lambdas.
You have Cloud Storage, which is, again, for static assets. You have hosting. You have Test Lab for Android, which is running Android unit tests on Google's device farms. And you have performance monitoring.
But this is like a feature overload, pretty much. What does this mean to you? Because everything I said before, blah, blah, blah, not relevant enough. So we get free CDN and SSL out of box.
We have easy auth so that you don't really let your messaging queue out there unauthenticated. You have a free tier, which, as a startup, you're probably not going to hit. You have file storage. And you have automatic magical scaling,
which, of course, Google, global scale, makes sense. You have quite a few wrappers for it. There's this case for various languages and libraries that you can use with any front-end framework you want. So there's Angular view, React.
And there's a lot of them, pretty much. So if you need it, you'll probably find it. To get started, basically, you want to create the message queue, pretty much. And the message queue is the actual Firebase database, so the real-time database. And you create it.
You create a new project. And you give it a name, select a region. And you're good to go. Your messaging queue will be in the database section of the, real-time database section of the console. You need to grab your config. You have three options. You have the iOS, Android, and web.
We'll get back to these later, and I'll show them in the code. But pretty much, you have everything ready to go. You click it, get it, put it in your app, build an application, and you're able to communicate
with the Firebase database. Now, the auth is very simple again. In this example, I showed how you can do a simple email password authentication. You set it up, and Google kind of encourages it because they won't let you write by default
to the database unless you have some form of authentication. However, the roles can be configured, so if you want to disable everything, you can just do that, but I wouldn't advise it. It's not great to do.
So, so far, seems pretty easy. I think I've gone through it in a few minutes, and this is pretty much what you have to do to set up the message queue in Firebase. My choice of framework, well, library,
because React's not a framework, it's a library. My choice of a library for it is React, and for React, you have a bunch of specific packages, which either, depending on what you have installed, will make more sense.
So for basic React, no state management, no anything, you could use React Fire. If you use for state management Redux, then you're probably gonna wanna go for React Redux Firebase, and there's the plain JavaScript one, which is provided by Google, which is the Firebase package.
For my project, as buzzwords, you're gonna hear Redux, because it's there for state management, React, because it's the front end bit, Python, because we're a Python conference,
and I used to be a Python developer. So, Redux Saga for managing side effects, and Firebase, of course, because that's the whole point of the talk. And this is hopefully what it's gonna look like at the end and you'll see, I'm gonna provide you with an URL,
you're gonna open the attendee web app, and the hub, I'll show on the big screen, and it's gonna be the incrementing number of claps and showing the bubble growing.
Hopefully, this is what it's gonna be, and yeah. Okay, so let's have a look at the code first. For the back end, like I said, Python. And I use Python 3.7, you can kind of make out by the fact that there's compiled files,
PYC files in there. There's the constants, which I use for just holding all my config, the username and password, the API key, everything that I need to build the Firebase object. The Firebasepy will, is the file that I keep
my database, Firebase interaction methods in. Well, they're not methods, they're functions. And then I have the requirements. For those of you who are not familiar, this is pretty much the equivalent of a package JSON. Or, yeah, I think so, that's it.
And server contains the controllers and building the application, setting up some rules for cores and all the cool stuff for just making it serve properly. The application only has two routes.
One is when the user joins, so whenever you open the URL, you're gonna get unique ID. And that's just the UID, so nothing fancy. And I'm gonna return it to the client so that you store it. You can do updates later with a reference. And this is where I'm gonna update the store.
It's gonna chain, it's gonna trigger the chain of events of bubbling and all the cool stuff. And this is the other one, which is the clap route, which does the, updates the number of claps
for that user ID on the Firebase database. Yeah, again, you update the Firebase for that user. Okay, and this is the application.
Again, a pretty standard boilerplate. I use the AIO HTTP, it comes with a library for doing, for configuring cores on the routes. And the two routes are join and clap. I set up the cores, never do this in production,
the rules are way too simple for it, and I didn't really wanna go into figuring out why I should set it in a certain way or not. I just use the book, everything. And then you set up the cores for every route you have in your application. And this is the config. So you get your API key, your auth domain,
a DBRL project ID, storage bucket, and sender ID. And then you just initialize your app. I love it how, so you see the Firebase initialize config. I love it how Python always does the funny names. It's very, yeah.
So yeah, Firebase initialized the app, and you have the object for your Firebase app. And then, authentication is very complicated right now. So you do the auth, and then you sign in. You get the user object, which has the token in it.
I'm gonna show you in just a minute how you use it. Yeah, and this is the Firebase. The Firebase, you grab the reference to the database. That's the first thing. So from the Firebase object we defined earlier, you find the, get the wrapped reference. We want to initialize the data on it,
because when the user joins, it's gonna have a class of zero, so do that. And then we insert the data into Firebase, and that's it. So basically you insert it, and that's it. The user token, user ID token at the end, see here,
you grab that object from before when you did the auth, and you always need to make sure you pass it in, because you set up authentication, so you want to have it there. It expires in one hour. Hopefully by demo time it's not gonna be one hour, because I don't have that.
Okay, and the update is a little bit different in that you don't have the default data. Yet, again, the reference, you get the previous number of cops, and then you implement it, again, passing in the user of ID token.
So the user did contain ID token, and it's gonna be valid for one hour. Front end is a little bit hairier. You have a long list of files, folders, actually, those are not files, they're folders. And you have the actions for triggering storage changes,
you have the assets for static stuff, you have components which will render your UI, you have the index JS, which is the main edge point, you can name it, whatever.
Okay, okay, test. This, okay, I hate my voice. So where was I, folder for the reducers. Okay, so the reducers are functions that will match an action and mutate the state,
and basically that's the only place you wanna mutate state, and most of the time you wanna do it in an immutable manner. So basically, create a copy of the store, mutate it, and return a new object.
Roots, for the roots, I took them out of the main entry point, because I wanted to have them separate and make them more readable. You can even split them. So as you go further and further, you're gonna have a lot of stuff, and it's gonna be confusing if you don't split them out.
SACAs are for managing side effects. By side effects, I mean something like Ajax requests, a long-running thing, and long-running processes, all that kind of cool stuff that if you do
have an application, you're gonna wanna have. And the store is where you wanna have the store definition and store configuration. But yeah, so far, JavaScript applications, especially large ones, are really bad, and if you don't maintain some form of structure,
you're gonna wind up with something like a rubber band ball and try to get the one in the middle. You know, it's like in the center. It's not gonna be fun. This is the entry point. Like I said, store for the application state and the routes which I conveniently factored out.
These are the routes. And as you can see, it makes, even to the untrained eye, you will probably notice that it's a component, and when you go to that route, it will render that component. It's pretty, and yeah, it's pretty cool to factor them out.
The main component of our application and the one that does actually reflect most of the functionality I wanna show is the hub. The hub listens to Firebase changes, and that's what we're gonna do. It's exactly after the component has finished mounting with rendering.
The JSX, if anyone's not familiar, this is JSX, it's a templating language for React, is three lines. Quite simple, and yeah, it's not, nothing more to see here.
And of course, always do validation on your props. It's good practice, and basically, your lint will complain if you don't, but I recommend it. It's an easy way to keep track of errors. Okay, now the component we saw before,
we need to wrap that into a container, and we can do that with connect, and we're gonna map all the actions to the props. So in our case, it's just the one where we start listening for data.
So okay, again, actions, still pretty simple. You're gonna have the listen I showed you before, but really nothing really complex going on here. The action type is a string, actually.
I just defined the action types as variables so that you can change them in one place. Initially, if you do work on an application, you wanna do it like this, because it saves time refactoring. And these are the reducers. For example, any one of them,
they're gonna check for the action type, and they're gonna try to match it. If they don't, they're just gonna return the default state, and always return the default state. It's a good way to not crash. But yeah, so far nothing.
So we haven't seen any of the real-time stuff. We haven't seen pretty much anything. That's out of the ordinary. So yeah. And then we have Redux Saga. Redux Saga is a nice way of, clicked it.
Redux Saga is a nice way of handling side effects. If you guys are familiar with Thunks or Epics, Epics is newer, but if you are familiar with Thunks, they've fulfilled pretty much the same, a similar purpose, but they give much more
fine-grained control over what you can do. So for example, you can throttle them, you can de-pounce them, you can cancel them in mid-flight. So that gives you really good control over what's going on. So yeah, the magic I was talking about is not a lot.
Don't be confused by the slide, but. So yeah, this is where the Redux Saga's place in the whole project, whole Redux workflow is. It's basically somewhere in between the action and the reducer, and it communicates directly with the API.
It's right there. So in our application, the way it's gonna happen is the UI will create an action, it will go into the Saga, and then the Saga will perform an API call,
the API will do some Firebase updates, and then it's gonna return, pop into the reducer, reducer updates the store state, and then you're gonna have the UI updated.
And those are just the basics, unfortunately. There's another one that's a little bit trickier, and because Firebase is real-time and it's an event pipeline, more or less, you're gonna have to use an event channel. And this one will listen continuously
for changes that are coming in. So yeah, let's have a look at the Sagas. My, so we're gonna import Firebase because we want to use it, of course, and then we have some Saga goodies
for performing our actions. We have the, you know, the Sagas come with a bunch of utils for managing either calling Ajax functions or dispatching other actions, and you also have the event channel
which we're gonna have a look at because this is the guide that's gonna help us you know, manage the real-time events coming in from Firebase. So the two points that need to be looked at
are the fact that you need to listen to Firebase changes, and this is, the database is just the Firebase object. If you remember in the Python slide, I showed the database with the, you grab the reference, that's, this is that reference, not from Python,
but it's built beforehand. Sorry, I'm stuttering. Okay, so yeah, you grab the database ref and you listen to changes on value. You can put anything in place of on value. There's like three types of change listeners.
And then you need to turn it off when you're done. And then we want to create a saga and use the event channel and keep listening to it. But we're gonna listen as a server does,
so it's pretty much, it's not gonna run continuously. It's more of a passive action and basically it observes for changes, pretty much. And then we wrap everything nicely in a root saga. This guy contains all the actions
that are being dispatched within the app, but you have the listen hub data action, which I showed you before. Okay, so I think we're gonna give the demo a go. So, okay, bear with me.
Can you guys hear me? This is the URL. If you guys wanna take it or,
I'm just gonna quit out of this. Let's have a look at the, if you guys have a QR code scanner, there's this. And if you want the URL shortener, there's the, no, wait, wait, that's the one.
That's the bit.ly URL. If you have a QR code scanner, you can use this. If it works, it's kinda sad about the distortion on the thing.
Did it work? Hmm? Did the QR work? Okay, do you find, do you see the, yeah, you have it?
Okay, and now we have a few, well, yeah, somebody joined, and then you have the guys clapping. Yeah, pretty interesting. No, really. To be honest, I wish I did it a little bit better,
a little bit, oh, there you go, another one. Somebody else joined. And this is going all through Firebase. If you wanna go to the thing, there's gonna be a, you can use that link to join if you haven't already, because I switched to the hub. Don't push the link off the screen, please.
And then, yeah, what can I, ah, yes. You know this, any of you guys used ng-rock before? So basically what's going on, this is on my laptop, and you're communicating
with the API on my laptop, and this pretty much gives you a quick way to do demos. So somebody's being bad, somebody's being bad. No, no, I zoomed in, no, and yeah,
that's the link again, okay, cool. You guys happy with it? Can I switch back to the slides, wanna play some more? How am I doing on time? Sorry, oh, how am I doing on time?
10 minutes, okay, okay. So yeah, I'm gonna stop it, is that okay? Okay, okay, this is it, ah.
You can find my code here. So the code for this demo is available here, and I'll take it, play around with it, I then submit the configs, because, you know, I don't wanna skip my free tier on Firebase.
Also, I don't want them to ban me. But yeah, it's there, and yeah. So you can find me on Twitter, you can find me afterwards, chat me up, ask me any questions you feel like, and you know, stay classy, Barcelona.
Thank you.