live code: Svelte app showing realtime Postgres data changes (GraphQL subscriptions)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
his web applications are expected to present real-time data and react to user actions in real-time as well as present changes in data in real-time to the user without the user having to refresh their browser or reload the page or anything like that so there might be several users using an applications at the same time and as they create data or update or modify data all the users should see the modifications in data on their browser you know without refreshing in real-time so that is the expectation and swell tis more than ready to do that especially we have swelled stores which are designed for that exact feature swell stores they can they can represent subscriptions and those subscriptions and the stores basically can rerender the page the swelled component that you're looking at in real time as the subscription the value of that encapsulated data changes within the subscription and we will see how we can use Postgres database and query it using craft QL mutated query 8 and also subscribe to live changes in real time and to do that we will use very nice open source software called Essaouira we will combine swelled stores with essaouira and Postgres database to create a real time to-do list so let's take a let's get started alright so the first thing we will do is create our basics world app so CD devs well then let me just say npx this is how we usually start all our result applications npx ticket well yes slash template and then we will call this a sir - to do okay then created let's open this application first thing we do is we run npm install good so once that has been done we try we can run there if you want and open that dev in Europe's I think I lost that so okay and open this localhost 5000 so that's right so this is our standard standard hello world from swell'd no problem let's remove extra stuff from this we can go into apt arts world and remove everything that we don't need which is almost everything and now we are going to add graph QL and everything else to it but before we do that let us download and run asura so in order to run Asura what we what we will do is we will so this is the Hazara website and what I will do is if I say Google and then say Asura darker if you do that and you see QuickStart with darker has to our hustler 1.0 documentation and click on the get darker compose file now all of this information I will include in my show notes as well as the source code but let's just copy this this URL and we go to my house for a directory I have created an empty directory and I am going to download that particular file so to download and save that file I am going you can do either dublicate and dublicate and then the file or in my case I have curls I will use curl - capital o so okay once I do that I have a darker compose file I can show you what it looks like in so this is our docker compose file mainly it has Postgres database and it has graph QL engine which is Hazara graphical engine version 1.1 point 0 and it exposes itself on port 8080 which is fine so now in order to run this you have to have darker installed if you don't have darker you can install it or you could just and download all the components which is have Postgres as well as install it on your on your laptop or in a server but I think docker is the easiest once you have that up and running all you have to do is say docker compose up - dear then detached mode I don't worry if you don't know it's alright there are other ways to run this so here I survive running now that's good now that that is running let me go to the console so if I go to localhost:8080 that's Sarah ok so now in here there are two tabs there are many tabs but the ones that I am interested in is graphical and data so first we will have to create a database table this is our interface a nice graphical interface to PostgreSQL database and graphical is a graph QL Explorer okay so let's first create a data base table so we click Add table sorry not add yeah that's fine yeah at table we will call it to do and in that table we will have a column called ID which will be of type integer Auto increment then next one will be the title which is the title of the to do of type text and the next one will be completed status that is the status of the to do and it will be boolean and we'll give it a default value of false okay then we select my key that's ID and I think this is it let's click Add table that's it so it created the table and the table has no rows at this point now that we have created the table let's go to graphical and start either querying or inserting into the table so well I guess since it has no no data in it let's start with an insert so the way you do insert is you can either click on the documentation Explorer or you can also hit this Explorer and then select a mutation and click plus so that has added mutation we will rename this mutation as insert to do then we click on this mutation type insert to do and it says in that or how do you want to what are the values you want to insert fields so we don't want we will not determine ID ID is going to be auto-generated but title and completed we can give now and then when the result arrives we click we want the number of affected rows or or or rather we want the ID in fact that's probably what we really want and number of rows and ID so now every time you are going to insert you're not going to use a blank title you are going to use a variable value so why don't we replace this with a dollar title variable and then create a parameter here called dollar sign title and the type of this will be string and it is required so we will say string exclamation sign once you do this you can you have a mutation that takes one parameter called title so let's create a variable called so if I say in the query variables I say curly brace in the press control space and it already tells me what variables it can take and the title is going to be I will call a title of or something or do something that's your to do okay and now if I hit graphical play this play button execute query it ran and look it has it says it returned an object the object object has one property called data which is another object has a property called insert to do and that is another object that has affected ROS equal to one and returning is an array first member of which is ID so now if I go to data and then run click on to do table and run the query it shows that we have something called to do I'll de qualité least do something and complete it false so this is good we are able to insert reduce let's try to insert this now that we have the basic understanding of what query we have to run let's go back to graphical and we will copy this mutation and then execute it from our swell'd application let's get back to swell'd application first thing we have to do is you stop this dev server because i am going to add a whole bunch of dependencies so now which dependencies we want we can find out by going to internet and say a search for Apollo client subscriptions API subscription let's see if we can find their first subscription client react we are not doing this in react we are doing this in in in swell'd but the basic basics will remain the same okay so one of the things is when you are doing this with Apollo client you make sure you do it with Apple Apollo client and not with not with Apolo boost okay so there are some different dependencies that we have to include when we are keep in mind we are going to do subscriptions now what are subscriptions subscriptions are basically queries that you run and they keep running and they keep producing new results in real time as long as the result is changing which means if you ran a query let me just show you actually it'll be easier to show them than this so let's let's look at a subscription I will create two two browsers instead of one so let me show you what a subscription looks like so this is the insert lets in in this tab we will create a subscription let's do that so clear this out and I will say in add new subscription and I will click plus on that and then my subscription will be would be called - dues subscription - dues you can say to this query okay so now we go to dues and we want to get these three items so here it is it's very simple there is no query variables and if I now execute this okay sorry it's it's a bit on the right so let me just make this smaller oh yeah so I ran this it on the right hand side you see the result of the subscription which shows us one particular to do let us now create in the left-hand side window let's now create a second to do and that will make it clear what a subscription is so there was one first to do was do something let's call it do some more now if I watch what happens in this window okay right now there is one to do shown and when I hit this play button and insert new to do on the right hand side you will see new data show up there you go this is the new data so this is what a subscription is if I if I do so let's say I do it again right and and then I hit play once again watch this area and then yet another one so this is what a subscription is a subscription is a query that reruns itself in real-time whenever the data changes okay now in order to make use of subscription we will basically what we will do is we will subscribe to like to this query and then we will use well stores to Rhea rerender and update the UI okay so in order to do that we have we will use this graphical client called Apollo client so what I did was I simply searched for Apollo client API subscriptions when I did that and the very first result was the correct one I click on that and now it says if you want to do subscription with graph QL you have to have some extra items so let's copy this so he says you have to install these NPM modules Apollo link WS and Apollo transport W so let's copy this or just click this and now we go to our IDE and paste this so NPM install save Apollo link WS means web socket and transport WS okay so I say that once I do that my package dot JSON now contains let's see what it contains it contains Apollo link WS and subscription transport there are a few other things that I actually need let me let me make sure I have those okay so I had it in my there it is this is the list of NPM modules that I need I need to install Apollo client Apollo cache in memory Apollo link HTTP Apollo link error Apollo link graph QL tag graph QL Apollo link WebSockets and subscriptions transport WebSocket so this is a longest list once again I will have the source code and this information available with the video let's press ENTER so it is adding a few different NPM packages now that that is done we can go back to coding so in our apt arts world what we will do is we will we want to insert a to do okay that's the first thing we want to do but before we insert that to do let's create a separate dot JS file which helps us connect to graph QL server that has Sora has created so let's call it graph QL - client GS and in there we will add a few things so now what should we add all that information is in my in in this this example so what you have to do is let's say copy and paste all of this copy from here and then paste into this okay a graphical client RJ so you we are let's now let's try to understand what we are doing we have when we want to query in real time through subscription we need WebSocket link but when we want to update or insert the to do we need HTTP link so that's why we need both and and the URL of our of our graph QL endpoint is localhost oops okay localhost sorry local host it's zero eight zero and then V 1 / graphic ul that and the HTTP link is protocol HTTP and then the WebSocket link is local hole WS : / / localhost 8 0 8 0 V 1 graph QL the same thing so the only difference between these two is one is lower HTTP the other is wso then web socket and the options reconnect is true so that if we lose the the connection the client tries to reconnect now this is important the split split and so we create a special link so there is an HTTP link there is a WebSocket link and there is a third link which is a combination of HTTP and WebSocket and how does it choose between WebSocket and HTTP you give it a lambda function which takes the complete operation type one of the things in there the query property with the structure that into query and then we use this get main definition this one from Apollo utilities and that allows us to parse the query you get some metadata information about the query and as long as the definition that kind is operation definition and the most importantly definition that operation is subscription if if this evaluates to true then we want to use WebSocket link otherwise we want to use HTTP links which means mutations and queries will go through HTTP link while subscriptions will go through the WS link okay now once you have all these things all you have to do is get yourself the Apollo client so the way you do that is you import Apollo client from Apollo client simple and when we and then from this file we say export default new Apollo client and so we are creating a new graph QL Apollo client and it takes in an options object and the options are going to be two options one is the cache and the link so the link is going to be link : link which of course you don't need to repeat you can simply say link and the second thing is cache the cache is going to be in memory cache so which we have to import so import in memory cache from Apollo cache in memory let me make sure that ethic yeah so right so once you do all that you have the in-memory cache and we just say new in memory cache that I think should be enough right so let's take a look again we have two types of links HTTP links link for queries and mutations WebSocket link for subscriptions and then we have a combined link which is created from the split function coming from below link and that's how they have a lambda function that checks that the operation is of type subscript and the operation is subscription if it is a subtraction then it uses the first one which is WebSocket otherwise for mutations and queries it uses HTTP link I like with those things in place I think we are ready to make a mutation query so first thing we do is in our app you say import let's say client from the current directory slash graph QL client dot yes and then once we have the client we are going to insert it so first let's build a form let's say form in there we will have an input type or type is text of course let's give it a placeholder enter to do title okay and that's your and then we have to bind it let's create a local variable called let to do is equal to an object with title is equal to blank okay and then we will add a button of type submit' and label submit what's format it and save it okay are we running no we are not running so let me run the dev server okay looks like it's it didn't give any compilation errors so that's your enter to do title and there is a submit button at this point this form will not do anything useful so let's add in on : submit handler and then make sure the default is prevented which because the default is to submit the form and we will give it a name give it a handler a JavaScript function let's call it save say no that's called insert to do all right so let's define that function we can say function insert to do but we will say async function to do insert to do why because we are going to be doing asynchronous activities such as inserting okay and when it does that the insert will simply insert this to do object whose title is bound to input which we forgot to bind so let's fun bind it say bind the input value to to do dot title so now title will be bound to this input okay now when we want to insert we want to execute a mutation query so let's say let's create a mutation body so we remember what the mutation query was of course I don't so let's find that mutation query here it is they insert to do mutation let's copy this and Const mutation is equal to now we have to import the gql tag the import gql from from graph QL client tag I think yeah so oh that's not that's the default exports so we don't have to do this so okay so we are importing the gql tag this tag is needed because we are going to wrap that tag around our actual mutation query so there it is so this is the mutation called insert to do it takes one parameter title which is of type string and then it calls insert to do with all these things okay and it will return your affected rows and the array of ID's that it inserted that's a now in order to actually do the mutation we have to say client which we got from graphical client which we have created dot mutate and then remember this is not a query this is a mutation so we have to say client dot mutate and then in there there are two parameters one is the query para an or query sorry mutation parameter yeah mutation and the mutation the value of that mutation is this mutation so we simply instead of saying mutation colon mutation we can just say mutation and the variables these are the parameters and the variables are going to be remember it takes one parameter called title so we have to say title is equal to two title so that's what it is going to insert let us see if this works so save it and let's say at this point our database let's look at the database oh why not look at this this is a real-time query it has three do something do some more and do it again right so if it gets the fourth one then we have succeeded okay let's call it keep doing it I don't know if this will succeed but I clicked enter and wow it worked there it is just keep doing it so so we have four troduce now that's great so which means our insert is working all we have to do now is get the subscription working at this point we are able to insert so let's let's see how to do subscription in order to do subscription we have to call let's say we have to yeah we have to say Const - deuce equal to client dot subscribe and then the subscribe takes one parameter which is the query so and the query is going to be what's Kippur what is our query the query is const query is equal to again gql traverse tick so these backticks allow us to make multi-line strings and now if I go to my subscription here's my subscription right here so that's my subscription copy it and then insert that body in here okay so this is what my query for the subscription looks like I want to get all the traduce completed ID entitle all three of them present now I will simply say query equal to yes colon query or I'll just be shortened it to say Corre so this gives me s so this is the magic of swell'd client not subscribe returns and observable and if you know anything about observables then you know that observables have a dot subscribe method and as you might know that in swell'd any JavaScript object with a subscribe method is a valid store and because it is a valid store it changes everything we can use that valid store to show us we can use that store to subscribe and then also repaint and re-render are swell to UI so let me explain I mean let me show you the code so the code is going to be let's create a table table table has a tea body tea body and tea party has a row right so we will say all the row is going to be repeated so let's say each pound sign each swelled has a pound sign loop and then we will say to dues now look at the response that we are getting we are getting to dues in that data to do which is an array so we can say to do is dot data dot to do as T problem is and then we can close the each the problem is to dues is a store so when you want to subscribe or to subscribe to the store remember this is graph QL subscription while when we say talk about subscribe here we are talking about swell subscribe store subscription so we have to put a sol de la sign in front of the store name and now we can say t our produce a row and in there put a TD sorry TD and show me the ID which we ste dot ID and then let's repeat this show me the ID show me the title and then finally show me the completed right now what we see is we are going to see the the two dues right so let us see if this works ok save this and we saved it and it didn't work something broke so if we inspect and look at the so here's my so it just cannot read property data of undefined in app dot swell line 49 which is this place ok so the problem there is that - in the beginning the there is no value stored in the store and therefore we have to wrap the whole thing in an if statement and we have to say if dollar - duze has a value dollar to dues dot data has a value right then only do the rest and we will close the if after this each oh I guess we don't want to show the whole table so let's put it outside yeah so let's close the F and let's reformat it re indent it so now when I save this oops I messed up yes so now when I save it look haha I got my table all my fault to dues are here do something one two three four do something do some more do it again keep doing it and the completed status is always false so if you wanted to have a heading you can put that heading right here D head and then again the same TR th the first one is ID second and third title and status completed status okay so you got the ID title status nice now the thing is let me let me this is very important it is so deceptively simple and it's made simple because of swelled and in this particular case graph QL and hussar are also helping all we did was client dot subscribe run this query and subscribe to it and keep rerunning it or keep returning new data as the data changes and here's the d subscription it's it's it's deceptively simple let's do a couple of more things you can actually do order by so so that new ones show up at the at the top so right now if i if i add a number five let's say five hit submit then five showed up look it it showed up in real time we did not create the subscription product the only problem is that five is at the bottom so if you want to show five at the top all we have to do is go into the secret loader and then oh there is an yeah open this order by and click ID instead of ascending and let's say descending so now when you do that it showed you what query you should see this is so helpful it says you should in your to do you have to give this parameter order by and with an object ID whose value property value is descending so now you can just add this to the query and once you do that and I save it and now everything shows up in the reverse order so highest ID is first and so now if I add in to do number six to do six right I hit and then to do six at the top great this is very nice and all of this is made possible by this Apollo client which is subscribing to a graph QL subscription the subscriptions are provided by Asura and hasari is storing everything in PostgreSQL and then swell'd store because this the subscription object has a subscribe method so it becomes automatically becomes a swelled store and now once you have a swell store you put a dollar sign in front of the the variable that is an auto subscribed operator and now you check the value that the troduce has a value and within that produce has data specifically once you have all those things then only you want to display the table and once you get into the table you say okay now loop over the to do store data dot to do st and then display that lets one more thing that we should do probably is you know when the when the to do they get completed we should have we should be able to update them yeah so when we are to do so instead of this hard this read-only status let us make it updatable so all we will do is in here instead of showing it like this we will say how about if we show a checkbox so we will create a label and the label wraps the value okay and then we will inject the checkbox right in the middle of it we will say input type checkbox' oh I lost everything okay let me just okay input type checkbox' and then the we will bind the checked property to t dot completed right so that's your input type checkbox' and now that's your label but we have to close the input checkbox and then within the body the text of the label is going to be if T is completed right then show completed or done let's say let's call it done show done otherwise show pending okay let's close this let's save it see what happens there you go so if you got all these check boxes now the thing is when this check box is changed they will change only within the browser's memory so we have to change it up on the server so in order to accomplish that we will okay and this might be a little bit harder for you to read because it's okay so what we will do let's see if I can okay yeah reformatting helps so if I now whenever it changes on change of the check box we should say update to do this update the completion status so in order for to do that we will create a new method function rather called update so there is this insert to do let's create let's say let's duplicate it it's this is going to be another mutation so copy and then paste so we just duplicated the method and now it's instead of insert it's going to be update now the thing about update is let's see use this graph QL Explorer once again to learn to update first of all we go back to the Explorer clear this one out because we want to insert we want to add new mutation and this mutation let's click Add and now in this mutation we want to update so let's hit update and what do we want to do we want to set the value of completed and where we have to have an ID clause where and that where is going to be that where ID is equal to something well in this case they gave us a hard-coded value but that's okay now once you have all that information you can go back and say update to do where ID is not going to be 10 it's going to be a variable so we will say dollar ID and let's make dollar ID a parameter so dollar sign ID it's of type integer so if you do this completion yet it should yeah so if you I'm pressing control space and that's the int integer and exclamation sign means it's required you have to give it and then instead of completely being false we are going to say completed is equal to dollar completed so and that is another parameter so we just add it here to the mutation dollar completed and it is of type boolean oops boolean and it is required okay now we will rename our mutation to update to oh okay the other thing is this thing the reason why it's showing an error is because you are not dealing with the result so let's deal with the result okay my I need to make this window bigger yes so let's deal with the result and we deal with it by putting curly braces behind at the end and then effect it rolls let's say the turn up effected rows now in order to update it let's look at the data that we have we have ID equal to let's say ID equal to 3 do it again let's make that complete it so we just say in parameters we gave give ID and the value of that ID is 3 and then the value of completed is going to be true so if I run this query mutation rather then a affected rows is this but then over here you will see ID 3 should have changed there it is completely equal to true everything else was the same in fact within our application look 3 got updated we did not refresh so this is working for all subscribers this is great so now all we have to do is come back copy this this query out of here and put it in here mutation paste oops we have to format it nicely indented properly ok so mutation update to do takes two parameters all this is good and now we call the same update agent line dot mutate give it this mutation and then variables instead of title we have to give two things one is the ID and the second ID okay so update to do should take a parameter and that parameter would be the to do that we are updating and we have to provide the ID which is the idea of the to do I'll equal to to do dot ID and then completed is to do dot completed right so this these two properties come from the to do object so now when we call a plate to do here we have to call it with that to do parameter so because as you know this is an event handler event handler will take an event which we are not using so instead we have to provide it with it to do and the that could do is T in here inside this each loop that to do is called T and now that to do will be assigned to this to do that T will be assigned to this to do and then we will use the ID and the completed status to update it all right let's see if this works save it okay now let us look at this let's look at this live query hopefully it will change let's may mark the first one do something as done okay so this is my do something I click pending and it is done so did it complete it good oh wait do something do something is completed true it's working Wow if I hit now to be very very sure you can also look at the a database so back in the database when you look at the to do's and the do something is completed true and do it again is also true others are false if I go to go and keep doing it make that I check that and look it came back initially did you see for a second it was a check the check box it was still pending and then a second later it became done that's because this subscription first we executed the mutation and then mutation executed and then sorry the mutation is the mutation yeah so this update to do this mutation is executed and took it it took a second for the subscription to realize that things have changed and the sub subscription gave a new updated value and that's how so now at this point if we check everything as spin and so if I check this and this and this everything is true now and back here if I you're under query in the database everything is true now if I uncheck to do six it's pending now if I run the query again then to do six is completed false and obviously this this live query subscription that is is also to do six completed false so this shows you how to now all of this was possible for some very very well chosen pieces of our architecture one is Postgres which is a nice database second thing is a surah now once again I will show you a surah is running over here and as Sara has two parts the graphed graphical Explorer graphical Explorer and then the database Explorer also which is this guy sohe surah basically puts a graph QL front-end on top of Postgres and then quite important then we used the Apollo client which gives us the ability to run queries and mutations as well as subscriptions and not only that it gives us the option of doing it with HTTP link as well as a WebSocket link and then it gives us an ability to split between the WebSocket and HTTP link based if so send everything to HTTP link except when the operation is of type subscription and then we combine those things into a single link and create an Apollo client and that Apollo client can be used for doing mutations and so insert to do mutation as well as update to do mutations and finally we run this subscription the so simple all you do is client or subscribe and give it the query and the query is very simple it simply looks for all the traduce and when you assign that to this local variable to deuce that becomes a swelled store why does it become a swell store because the client or subscribe method returns as you can see here it returns a it returns an observable that's the important thing because it returns an observable observables and you might know have a dart subscribe method this which is different from this method okay so Toulouse dot SUBSCRIBE makes it a and UPS observer makes it as well store and now once you once it is a swell store you can put a dollar sign operator in front of it prefixed dollar sign and now use it like a local variable which is Auto subscribe and it's variable the value the store value is extracted and we check that there is a value and there is some data in it and then run and show this table so this is our very simple clean example very few lines like you know in 8090 lines we have this and then a little bit of the code here so creating real time applications is is quite easy I would say in swelled and I think that we should yeah so let me just show you the slides yeah so creating real time application is is quite easy now with swelled so I hope you found that satisfying and edifying because swelled makes creation of real-time applications very easy combined with you can do this in firebase of course a lot of people do to do apps real-time apps inspire base but the problem with firebase is that is it's owned by Google you are not hosting it yourself here Asura and Postgres is something you can host yourself on your own server in the controller all your costs everything is within your control so in that sense it's very helpful also keep in mind the wavy installed Asura it's a all the permissions are open the security has not been tightened so you would have to fix all that you can get more information about Asura by going to Suraj I oh here it is surah dot IO and like I said you can get that the docker container which will give you both graph QL front-end a graphical server as well as Postgres so and that is how we are able to create these swell tap apps that are updating in real time look at that so hope you learned something please subscribe and comment and like and let me know what what other types of videos you would like to see I have been getting some good feedback and that is very encouraging that is what drives me to create more videos and make them you know as useful educational as possible we will keep doing more swell videos and I do believe that wealth has the potential to replace react as the primary the most favorite JavaScript UI framework or a compiler I would say so let's let's make sure that we spread the information about wealth and and make JavaScript UI applications easy to create and very very smooth pleasurable and increase developer productivity Thanks
Info
Channel: SpinSpire
Views: 3,749
Rating: 4.9603958 out of 5
Keywords: ReactJS, sveltejs, javascript, nodejs, postgres, graphql, hasura, realtime
Id: HX5cqBkNJA0
Channel Id: undefined
Length: 53min 46sec (3226 seconds)
Published: Mon Feb 24 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.