Build a Serverless API with Firebase cloud functions, TypeScript and Firestore

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey hello and welcome today i'm gonna be introducing firebase to you and we'll learn how to build a rest api with firebase cloud functions typescript and firestore so prerequisites for this course is knowledge of a rest api's knowledge of typescript and knowledge of the express.js framework now we are in the firebase homepage and you can access firebase homepage by navigating to firebase.google.com on your url address bar or firebase.com or you can search for firebase on google and that should be the first thing that shows up we have a firebase home page and depending on when you open this home page it'll look really different because currently firebase has a css problem and look at that that's why i've highlighted this so that we can see the text firebase helps you build and run successful apps backed by google and lot by app development teams from startups to global enterprises so our application is going to be a serverless application and what does that mean there's no much difference between this and what you've been doing before in terms of building a rest apis the only difference is that now we won't have to worry about managing the server setting up and running servers and being upfront for a particular period of months or years and all that stuff we won't have to worry about what goes on with the service all we need to worry about is the development side of it so firebase service applications is not taken away back-end jobs or we are still doing the development side if it's taking anything is the devops path but that still need that because someone has to set up all these things so it's just making our lives easier it's not taking anyone's job and that's what serverless is we can easily develop scalable and high quality applications without worrying about the cost of setting up and maintaining servers for a long period of time from the onset that's what serverless applications are and we'll be using firebase as our serverless application solution now we click on the get started button to get started when we click on this get started button or we should be taken to the firebase console and you can access the console directly by navigating to console.firebase.google.com now on the firebase console you probably see something different because i'm guessing you've not created the firebase project before so if you're new to firebase if you've not created a project before you see a different interface from what we have here and then another thing i'd like to point out is i'm signed into my google account so once you have a google account and you're signed in you will need to register or sign up for firebase you have a firebase account automatically right now in the firebase console no matter what you see you see buttons that have a text with an information similar to this add project we click on the add project button to add a new firebase project this is where we want to store our cloud functions cloud functions are similar to controllers in your rest apis not much difference again and we'll see what we're talking about here let's build a project we'll start with the name for our project now we can write whatever name we want inside here our application is going to be a journal rest api where we can add entry we have a journal or a diary where you can add different entries daily to our journal and should be made up of title um text and maybe we can add another field a cover image url so we can post title text convey material to our database and we'll be using firestore a database from firebase to manage data in application we can use any name for our projects here right now i want to go with rest api journal okay we can see that now project name can be anything but then there's also a project id underneath the project name and that has to be unique so if the rest api journal has not been used before for a project id or we get that here where the project id is supposed to be beside this pencil button but if it has been used before let's say we want something like um journal and yeah it looks like someone has used that before look at that so we have an extra string which is being suggested for us we can decide to change this to something else but it has to be unique let's go back to what we had before rest api journal should do and you click on the continue button to create your firebase project google analytics for your firebase project firebase offers is integration with different google services like google analytics google ads and so on we click on continue for this you might want to enable it you might not want to enable it that's your choice choose a create a google analytics account if you did that you click on the default account for firebase or create a new account then finally create projects to create your firebase project look at that your new project is ready click on the continue button to continue now we've been taking to our project overview page we see that we have a new project created for rest api journal and we're currently on the spark plan this is the default billing plan for firebase and it's free but there are different limits to this particular free plan we want to be using the cloud function service from firebase and when we click on these functions part so we see that on the left hand pin there's a develop section um if you don't have that open you see develop quality on analytics you click on develop and we have authentication cloud firestore real-time databases so these are the two different databases that firebase offers the cloud firestore database and the real-time database what we're going to be using for our application is the cloud firestore database now we click on functions to get started with our firebase functions and you can see here run your mobile backend without managing servers to use functions upgrade your project's billing plan so we can't use functions with the spark plan we'll also upgrade our projects billing plan to the blaze pay as you go plan now when we come over to the prices section of firebase or we can compare the different prices for the different plans and for the free plan the authentication service is 10k per month cloud firestore um we have one gigabytes in total for the free plan network egress document right you can come over here and see the different comparisons for the different services for these different plans but for cloud functions see that it's limited to nodejs 8 runtime which has been deprecated in firebase and that is why we don't have the option to use node.js version 8 in our cloud functions before now that would have been possible we could go with node.js version 8 and we'll be able to use cloud functions with the spark free plan but version 8 has been dedicated in firebase we will only be able to version 10 of node.js or version 12 of node.js so when we come back to the firebase pricing and go over to the blaze pay as you go plan let's see what we have in cloud functions now this is similar to the spark free plan just that when we get to a particular limit we have made a particular number of calls to our apis or use the particular amount of data in our database then we'll start getting built so look at this for cloud functions node.js 10 or later on times require the pay as you go blaze plan so for invocations free for up to 2 million invocations per month then 0.4 dollar per million invocation so we'll need the cloud functions but the good news is that we're not going to spend up to 0.1 dollar right now in setting up a firebase application and using this journal rest api that we'll be creating so don't worry about price right now what you're going to do is click the upgrade project and then you'll be able to provide a credit card you probably get built like 0.1 or a really small amount of money from my account i've already set up a credit card so i wouldn't need to do that again see that we have an info here you will now be charged based on your usage of database storage hosting machine learning test lab functions and google cloud services click on purchase to continue we have the blaze first you go plan now you can set a budget a lot i like setting the budget a lot for one dollar so i would know once i start getting built and do whatever i want to do about it i think you can set for like 0.5 dollar yeah you can set for like 0.5 dollar you can set for less than that or more than that so for this demo since you're building a demo application please set a budget a lot for a very very small amount of money so that you know when something starts going wrong or in a way that you did not expect so we set our budget a lot and we have that you've successfully upgraded your project click on the close button now that we've upgraded our projects we can use the cloud function service of firebase the next thing we'll be needing is the cloud firestore service so this is the firestore database for firebase we have the cloud firestore real-time updates powerful queries and automatic scaling it's a nosql database for mobile web and server development and it offers a seamless integration with firebase cloud functions you'll see how straightforward that is now to create a firestore database all we need to do is click on the create database button and then we should see a pop-up starting production mode or starting test mode now for production mode your data will be private by default client read slash write access will only be granted as specified by your security rules and for test mode your data will be open by default so what i like to do is always start in production mode for test mode anyone with your database information can read and write to your database but for production mode we need to create a security account and provide access to different people now we'll start in production mode so that i'll show you how to access your database through your security rules now we start in production mode and we click on the next button your location setting is where your cloud files or data will be stored so i like to go with the default and then click on enable now we have a cloud firestore database for our journal rest api project now that we have a cloud function service setup and the cloud firestore database setup let's write our first cloud function to start writing our cloud functions let's navigate to a project directory of our choice in our file manager or via a terminal and then we open the terminal i'm going to be using kit bash so git bash here you can use any terminal you want with our terminal open the first thing we're going to do is confirm that we have node.js installed so to do that that's node version and see that i have node.js installed if this returns an error message then you can install node.js by going to google.com and searching for node.js try to install version 10 since this is what we'll be using for our firebase cloud functions so when we come back to the firebase cloud functions page and click on the get started button see that we have an instruction here to use functions you need to install firebase command line tools using npm so once you have node.js installed you'll have npm installed too the node.js installation comes with npm now we can copy this command and paste it in our terminal click the enter button and we should have the firebase tools installed since i already have the firebase tools installed i'm just going to cancel this and now that we have the firebase tools installed we can decide to create a new directory for our project um let's say we want to name this rest api journal or we can now use the command firebase login to log into firebase on a terminal we run this command and we should be taken to a browser where we can complete the authentication i'm already logged in so you can see this already logged in as evidence at down dot official gmail.com now that we have the firebase tools installed and we've logged into firebase on our command line we can now create a new firebase function by running this command firebase in its functions click on the enter button and look at what we have here you're about to initialize the firebase project in this directory are you ready to proceed um i'm gonna click on no because i'm not change directory into the new one we created so click on no to cancel and then the next thing i'm gonna do is cd into the new directory created and that's rest api journal now that i'm in rest api journal i can now run the firebase init functions command again are you ready to proceed y for yes and look at what we have here first let's associate this project directly with the firebase project you can create multiple project aliases by running firebase use ad but for now we'll just set up a default project so if we had not created a project from the firebase console what we'll do is navigate to this create a new project option but we already have an existing project so click on use an existing project and now we have different suggestions from a firebase project so the dairy app api journal diary api rest api journal and social happiness so we are just going to use the rest api journal which we just created we select that and look at it the functions directory will be created in your project with a node.js package pre-configured functions can be deployed with firebase deploy what language would you like to write cloud functions and let's use typescript we select typescript and the next we have is you want to use eslint to cache rebootbox and enforce style or we'll be skipping this for our project and the next option is you want to install dependencies with npm now yes we do look at that we've successfully initialized firebase and firebase cloud functions for our project let's open this with vs code i'm going to use this codes commands with the full stop or you can go over to where you have the project in your file manager right click on it and then open with code depending on whatever operating system you have just try to open that folder in a text editor like vs code so click on the enter button to run the command and we should have vs code open up for us now here's our code base the rest api journal see that we already have default files that came with the firebase initialization we have the firebase rrc file which contains the default configuration for firebase we also have the firebase.json file we wouldn't need to be touching all these right now what we are focused on is these functions directory and inside the functions directory you see that we have a package.json file we don't have the packet.json file in the root directory we have that package.json file in the functions directory that means that whenever i want to run any of these commands to build serve shell start deploy logs any of these commands we will need to navigate to the functions directory of our rest api journal app not from the root directory we also have the src directory inside the functions directory and when we come over to the index.ts file you can see that we already have an example function which has been commented out let's uncomment this so we see it's more clearly now look at this start writing 5-bit functions https google.com i'm just going to make this bigger all right that's better first of all we're important functions from firebase functions and this is what we'll be using to create our function so you can see the first function here export cost hello world you call the functions.https.on request and this on request method expects a function as is argument a function has the request param and the response parameter the next we have is a functions logger that logs headlocks and then responsor sends hello from firebase to test this default function what we're going to do is go back to the terminal and then in our terminal we'll navigate to the functions directory right in the functions directory we run the command npm run deploy this should deploy a cloud function to firebase in this case a helloworld function look at that a function has been successfully deployed now to see a function in action what we're going to do is go back to the firebase console in our browser and right in the firebase console we will load this page or we should now see our first cloud function that's the hello world function the name of the function is hello world and the triggers url is this that we can see right here it has a project id in it and then slash hello world so let's test that out amazing hello from firebase so we've successfully deployed our first cloud function and it works really well the application will be a little more complex than what we have here we would want to use added functionalities like middleware so we'll be needing the express framework for our journal rest api with the express framework we can easily manage routing from our code base and use middleware we would want to use an authentication middleware middleware for checking user inputs and so on and so forth so let's see how to set up express js for our cloud functions all right to start using express in our application we'll come back to the terminal and remember that we're still in the functions directory now inside the terminal we run the command npm i dash s express so i'm assuming that you've used these technologies before node.js express.js and typescript so what is new to us is firebase the cloud functions and firestore also we have express installed now we can use it in our application let's go back to a text editor about vs codes what we're going to do right inside the index.ts file is imports express so in porsta pass express from express i've gotten used to writing javascript without the semicolon so i'm just going to get rid of it and we have uh two import statements the next thing we're going to do is initialize express with const app equal to express and that's what we want to export from my index or ts file so we'll take this app variable on line four and instead of declaring a new function inside our functions.http.onrequest method what we're going to do is use app as its arguments and with that then we don't want to put this in the helloworld variable we're just going to export this from our index.cs file so we have this export.app equal to functions.https.on request app so this supposed to be exports all rights the next thing we're going to do is add a test route for express app so to do that app.get and let's use the base url slash a comma and then we have the request and the response then where's the status 200 just sent [Music] hey there so this is just like building any other express application when a user navigates to uh base routes they will receive a response hey there to test this out we'll go back to our terminal and redeploy our application so to do that remember you have to be in the functions directory and then run the command npm run deploy also we've successfully deployed our application now let's see what this looks like in our browser back to our browser and in the functions page you notice that we now have an app function right here if you don't see yours you'll have to refresh the page to test out our application we'll navigate to this link so i should be able to go to this particular link and look at that hey there so our function works correctly our express application is working just fine now that that is done the next thing we're going to do is create a service account we'll use this to access a firestore database so let's come back to the firebase console and to create a service account we'll come over to this settings icon click on it and then project settings we'll go back to the service accounts page next thing we'll do is create service account select node.js and generates new private key your private key gives access to your projects firebase services keep it confidential and illustrating the public repository so click on generate key and we should have that so that's downloaded what we'll do next is open this uh download that file and then we have a service account details now we can pick this file and then put it directly in our project um folder so we can take this file from wherever it is right now right now it's in downloads and then you have that file in the download so that we can copy it and put it in our projects directory then use it from there but we don't want to do that because we'll be pushing this project to maybe a github account or you know a um public repository so what we are going to do instead is add the different information we need from this file to our firebase environment variable let's see how we can do that right now we're in the firebase documentation and this is the part for environment configuration so when we scroll down we see that this is the command to run if you want to add a key to the environment variable on firebase we run this command on our terminal so firebase functions config sets then the name of the key some service dot key so for example when you come back to where we have a project information we have the project id which is rest api channel so if we were to save that in the environment variable we're going to save it as project dot id so it should be namespace using periods private.keyproject.id client.emailclien.id and so on and so forth now back here we're going to copy this code sample and then we'll paste it on our terminal and edit the information there our back to our terminal now let's paste the code we just copied i'm going to expand this so we can see it more clearly all right so the different information we need for our application are the private key the project id and the client email let's first of all get the private key so that's this on line five or we're going to copy from here and i'll just go to the end of the line then i'll copy this next thing we'll do is go back to our terminal and paste it here so um i'm going to edit this some service dot key to private.key the api key is going to be right here and right click to paste we can see page there okay now that we have that the next thing we need is the project id so instead of some service dot id we have project dot id back to our code detail we can see our project id right here rest api journal so let's copy that and then we'll paste it right here so i'm going to remove this client id and paste the project id remember i'm recommending this so that we don't expose this um private key this sensitive information to the public normally what using the firebase documentation is um using the file directly in our code base so we have the the next thing we need is the client email so client.email and then equal to let's get the client email so that's this one right here on line six we copy that to go back to the terminal and paste awesome look at that so let's enter okay we've successfully added that now that we have the information in our firebase environment variable or we can go ahead to delete this file as we wouldn't be needing it anymore so let's close it you can delete it later on the next thing we're going to do is create a firebase configuration file so to do that let's come over to the src folder and create a new folder named config and inside our config folder we'll create a new file we'll name that firebase.cs so that's that firebase.cs file inside of firebase.ts file we'll start by importing a firebase admin so import star as admin from firebase admin next we're going to import firebase functions so i will use these functions to access our environment variables so that's firebase functions i hope that's correct was the problem import star as function let's see function is a reserved word oh yeah functions awesome the next thing we'll do is add mean dot initialize app so this initializes application and then gives us access to the firebase admin now this initialize app method is expecting an object with the credentials so oh start with our credential and then inside here for credential admin.credential.com cert i think that should mean certification and inside it i will start with the private key so private key and then to access our environment variable for the private scheme we stored earlier functions.config dot private key um let's clear this up so i can see what i'm doing so private dot key remember it's name space with the dots the full stop so private.key and what we're going to do next remember our private key um has so many words and um has like different new lines in it so we are going to use wedgex to replace those new lines so it has a new line with something like this double backwards slash n and then let's replace that with just this if we don't do that we'll receive an error so you can try it out without this dodge replace method and then you should receive an error so this is the key dot replace so we're just replacing the double slash n2 slash n and then we have the next one which is project id so project id functions dot config dot project dot id okay so that's for that we'll also need the client email so client email functions dot config dot clients dot email okay so that's that now we have that um we'll also add the database url this is still in our object so this is still in the objects arguments we are supplying to the admin.initializer method so database url and then what's a database url so that should be https um what's name of our application that's rest api journal so rest api journal dot firebase io.com so the database url is usually the name of the project.firebaseio.com now that we have the database url we have a we've initialized our admin the next thing we're going to do is get a database so to do that cons db will be equal to admin dot firestore so that's a firestore database now finally let's export the admin and the db we'll be needing them both we have that we have a firebase.cs file configured set up next thing we're going to do is use it so back to our index.cs file what we want to do is create a controller file so so that we can have the different controllers for adding information to a database files a database getting information from it updating and deleting instead of writing everything inside the index.js file let's just create an entry controller.ts file now we should do that right inside the src folder so new file then entry controller dot cs file so we use this to write a different controllers now inside our entry controller.cs file we'll start by importing a response so that's a response type and we import that from express the next thing we're going to do is import a database db from so this is um does slash config slash firebase now that we have that we want to declare a type for our entries so this is with a type keyword and then let's name this entry type our entries should have a title and a text so let's just use those two so the title is a string and the text is a string let's also create a type for our request so we have the type of response we'll create the type for request and inside the type for requests we'll need the body to be entry type next thing we'll need is paragraphs so when we are updating um entries in our database we'll need to provide ids so we want to send a rest request to update a particular entry we need to provide the id for that particular entry so that's why we're adding it to our parameter here so for params we have entry id and that is a string okay so we have the entry type and we have the request let's create um a function for adding entries so const add entry is equal to so let's make this asynchronous async and then request is the request type we have right there and we have response as the response type we imported from express so request and response and then we provide content for our function so let's first of all destructure the two information we'll need from the body so that's the title and the text so we need those two from rec.body so that's rec.body now we're going to make a database request next so we want to send a creation request i want to tell that database to create a particular entry so we're sending this information we have from rec.body to firebase and say oh firebase creates you know something in our firestore database what we're going to do is wrap our requests in a try catch block so we have a try and then inside it let's add a request we'll start with a const entry and this is so that when we have an error with sending information to the database we get our error message so cost entry is equal to db dot collection so you remember we imported our database right here on line two that's db db.collection and then entries so what are collections in firestore so firestore is a non-relational database and it's similar to mongodb you have your collections and in those collections you have your documents so we want to create a new document for our entry and to do that we'll have to specify the collection where we want to create that document so this is the entries collection and then doc this is creating the new document so what's going to happen here is that faster will look for a collection named entries in the database and if it does not see any collection named entries it's going to create one for us and then create that new document in it so we have a new firestore document what we're going to do next is create a entry object so this is what we want to put in the entry remember we just created the document now we want to create the object we will be putting in the document now our entry object has an id so the reason we are creating this document first of all before adding the entry object is so that we can also include the id um as part of the document information what we want is that when we find a document it should come with its id to do that we'll have to store the id inside that document so right now this document is here the document has an id to access the document id you have to do this entry dot id entry.id will give us this particular document id so let's use that now this is the entry object and inside our entry object we have the id and to access our id the document that's entry dot id so we have that and then we have the title and we have the text all right next thing we're going to do is use the set method to update our entry so entry dot sets entry object so right now here's what we did first of all we created a new document that's this entry divider collection um entries. so we created a new document inside the entries collection and then what we're doing online 24 is we're updating our documents to this new information here so to the entry object information the id the title the text so we use entry.set to set information in a firestore document now that we have that the next thing we're going to do is send over our response so that's responsive status and it's two hundred dollars and remember this is in the try catch block so oh we're all we are assuming that this is successful if it's successful we have this we're sending this over to our user so response of status 200. and then inside this we have status as success we have a message entry added successfully then we have the data that's the entry object so let's send that back to the user also um with that done or we also need a catch block so that's the try and then this is the catch we have the error right here we open brackets rest.tattoos so which means that this is a 500 error you want to do all that form of validation like maybe user input validation and all the rest you'll be able to do that through middleware so since we've already set up our firebase functions to use express you can easily ask me to wear for validation and then send the custom status response so right now let's assume it's 500 error and then inside the adjacent response we have the error dot message okay with that done let's see if we have any red lines no there's no red line all right let's export and next we'll go back to our index.cs file let's import the other entry function so import from that should be entry controller then we'll see what we have here that's the editor function next app.gets remember this is like working with any other express application this is entries and okay what i want to do is post rather so app.posts and entries this is the function add entry if you are if you ever want to add any other media where we can do that just before here so um validates user inputs and then send the customer without middleware and all the rest so this is our ad entry right here this is the route app.post to slash entries we have an ad entry function let's save that and redeploy our application back to the terminal we have npm run deploy to test this we will need a rest api client like postman you can convert your browser and search for postmatch that's p-o-s-t-m-a-n so you have postman and then click on the first link you see probably www.postman.com then install postman set it up it's pretty straightforward to set it up all right with postman installed and set up in a computer we can go ahead to make a post request first of all what we're going to do is go over to the firebase console and let's get the url for our application so this is the url copy that back to the postman application or paste that in this um url bar so this is the place we paste our urls instead of gets what we want to do is post we want to make a post request so we have this and then we have this let's come over to the body section and we'll use the x form url and code that's to send our request so for this we need the key value pads we need title and we need text so let's have ties before text so we need the title and we need the text okay what's our title let's say my very first entry so my very first entry and then for text we can use this is my very first journal entry okay then click on the send button see we have an error cannot posts and that is because when we come over to a url or we're supposed to be sending this request to slash entries and not just slash app so this is what we specified in our code slash entries we're supposed to be sending the post request to slash entries now let's send this request again nice success entry added successfully and we have our entry id a very first entry that is my very first journal entry um what we're going to do next is try sending this um without um the text field so remember the title and the text field are required so let's try um sending this without a required field we click on the send button and you see that we have an error value for argument is not a valid faster document this is a catch block in action that's why we needed the dry catch blocks but you probably need um a custom meteor validation for this purpose because this is a returning 500 error for us it's not supposed to be a 500 error this is a user request error is a user input error so you probably need to catch that with a middleware before you even send it to firestore now that we've created our very first entry let's go back to the firebase console and see the information we have in the firestore database back to our firebase console we'll click on the firestore section and you see our database so we have the entries collection created for us we have a new document this is the document id and then you have the field so normally if we had not added the entry dot id as part of the fields we'll have just text and title and then we can see the document id here but the problem would be that we won't be able to access this document id when we send the get request for our entry that's why we needed to add the id as a field in the entry body so we have a very first entry now we've been able to post information to a firestore database let's see how we can get information through our firebase functions to create a function for getting entries we'll go back to the entry controller.cs file and um right beneath the add entry function let's create a new function we'll name that get all entries so we use this to get all the entries in our fire store and database so get all entries and then this is a function our function parameters are remember we need the request and the response so let's copy this and paste it right inside here on line 36 okay we have that um let's add information for our get all entries function inside the try catch block again and let's add the catch immediately so we don't forget so the catch and then the arrow this should be return arrest or status um 500 let's move this to a new line so that's return resource status 500 dot json and error dot message okay we have a cache block now for the try block this is um all entries variable and we're going to create an all entries variable this will store all the entries we're getting from the firestore database we want to use the our weight keyword here to get entries from the database so to do that we'll have to make this function an asynchronous function so a sync and then a weight db dot collection we have an error we'll check out what that is in a bit so we have entries and dot gets okay so um dot get is used to fetch data from firestore collection so we're trying to get all the documents in this entries collection let's see what the error is so cannot find name async a s y and c and this is because we have an extra parenthesis right here so let's remove that you see that um the error is gone so async the request and the response now we have all the entries inside this particular entries variable which we've gotten from the db.collection method and then dot gets what we're going to do next is return so rest of status and then 200 dot json so the json and all entries so we have all the entries rights by one access the documents um in this all entries available so all those entries from the collection to access the documents and it's um i will use the docs property so the docs give us other documents in our entries collection now that we have that um we have the catch block we have to try block what we'll do next is export our gets all entries function so get all entries will export that and go back to the index.cs file app.gets slash entry so the difference is the one on the line eight is output post and this is app.gets so slash entries and gets all entries so that's it's automatically imported for us now let's redeploy our application and test it out deploy complete let's test it out with postman okay so instead of posts or we're gonna use get so select get and send we have an error message 400 bad request let's try that again but without the title send and see that we have a response so look at our entry this is my very first journal entry my very first entry um so that's a title and this is the text we have the id when we scroll down or we see that there's something strange and that's a private information we are trying to hide or we can see it right now when making the get request so if a user makes a get request to application they can see that private key that we've been trying to hide the one we had to um use our environment variables for so how do we get that out of here so firebase does not have um any out of the box or way to do this um there's no straightforward way to do this in firebase all we'll do instead is filter out um just this data and then remove this private key before sending the information back to the user so let's go to our code editor inside our code editor these are get entries function and what we're going to do is create um an orange so this particular all entries variable let's have it as an empty array instead so oh this should be the entry type remember we created an entry type earlier that's this one right here so this is the entry type for all entries variable and it's an array and by default it's empty so what's the error message i receive in here um okay okay so this is not equal to this is the column so the all entry type is the entry type um array for the entry array of the entry type and then its value is an empty iv by default we want to push um the document the one we need we want to push the information we need inside this all entries variables so or we're going to use the query snapshot query snapshot just contains um firebase documents so query snapshots that's what we'll name this particular variable and that's what we had before awaitsdb.com just what we had before it's a query snapshot so that's what firestore calls it dot get and that's a query snapshot what we're gonna do next is filter out um just the data from our documents and leave the sensitive information we're trying to hide from the user so let's use this for each method so query snapshot does for each and then inside this we have um a dock so this is the parameter we're giving it and the type should be on any type because we can't just easily get the type for uh fire store firebase documents i think that should be available somewhere but it's it was very difficult to find so we need the all entries variable and dot push and then doc.data so this should give us just the data we need other information we need now we have our um all entries variable and we have um the data we need inside the all entries variable what we're going to do next is just send the all entries variable back to the user we've already gotten the doctor data from our collection our entries collection now we have written rest of status 200 json all entries then our catch methods and that let's try this out so we just save and redeploy oh we have that deployed let's test it out on postman oh we click the send button and awesome we have just the information we need text is my very first journal entry id and title nice so we've seen how to post entries or database or is now the get entries from our database let's see how to update entries in our database and then delete entries from our database back to the entry controller.cs file we'll create a new function and name it update entry so const updates entry and then this is an asynchronous function so we have the async keyword then our request the request type and the response the response type let's structure a text title we'll also need the entry id so we all will get all of this from the request so we're gonna do is first of all get the text and the title from body next we'll get the entry id from param so remember we're trying to update a particular entry so we need the entry id now we have that um let's get this from rec so that's a request the try catch block again and then entry that's equal to db.collection and then this is the entries collection dot document and we're trying to get a particular document so we have the doc but this time around we're not going to stop here we'll include the id for that document so inside this doc method we're going to add the entry id so we're getting this particular entry now we have the entry the next thing we're going to do is update the entry remember to update an entry we will need the dot set method so entry dot set and then the new object for our entry but before that we want to get the current data from my entry so just in case these i want to update just the text without the title or get the current data so the current title in the firestore database we'll get that current title and then add it to the request let's see how to do that we have the current data variable and then we're getting current data so to get the current data we're going to call the entry.getmethod so let's put this inside the parenthesis since we want to use the which keyword so this is entry.get and then dot data with this we have a current data so this is the current data from the entry document that we've gotten from line 52 so this is data just in case this is not available we have an nc object now we have that let's create our entry object so const entry object is equal to we have the title this is title we're getting from our requests if it's not available then let's use the title from current data so this is current data dot title let's use the current title in the database so if the user does not provide any title we'll use the one in the database currently i will also do the same thing for text we have text from the user and if that is not available let's use the one from the database so currentdata.txt we have our entry object next we are going to use the entry.set method to update our entry so entry dot set and then the entry object entry.set and then the entry object and we should do this with our weight keyword since we're making a call to um a faster database our weight entry dot set then the entry object next return rest.status st80us this is 200.json and inside this we have the status success a message should be entry update that successfully then we have our data which is the entry object okay so this only gets sent if this um what we have on line 60 successful now that we have that let's include a catch block so this is a catch block right here and then arrow return rest.status 500 dot json error.message this is the function for updating an entry let's add the one for deleting an entry then test both at the same time so we have for update entry let's add for deleting entry so constellate entry this next and let's get the entry id so we're trying to delete a particular entry we don't need um a body we just need the id we'll get the entry id from our parameter rec dot params that's for the entry id then a try catch block inside it we have our entry we get the entry phase before deleting its entry db.collection remember this is the entries collection dot dot so that particular document and then inside the doc method we have entry id the next thing we're going to do is use the delete method our entry has a delete method that's the firebase document entry dot delete they should delete our entry next thing we're going to do is return a restart status we have the status right here and then message all right so we have that what do we need next we need a catch block next next i will export the two functions we just created that's the update entry and the delete entry back to our index.cs file we'll add the route for those two functions we have app.patch for updates so we are going to use patch for updates and then slash entry slash remember we're expecting um an id param so this entry id and then we have our updates entry [Music] next we have the after delete slash entries slash remember we also expect the entry id as a parameter and then we have the delete entry function we'll also need to import that delete entry nice we'll save this and then redeploy we have that deployed unless there's a new function back to postman we'll need this particular id to be able to edit or delete it so we'll copy that id and then slash entries still the same url but this time around we want the patch method we have the patch right there and we'll need the body inside our body section we have the title and we have the text this is my very first entry right now let's make this my updated first entry and then this is my updated first entry okay first journal entry we have an error cannot patch the slash entries remember our application is expecting an entry id param so this is slash the entry id we copied initially then click on send awesome look at that success entry updated successfully i use my update first entry instead of my updated first entry i want to change this right now but i don't want to change the text what we can do is remove the text and then click on the send button again nice look at that we still have a title and we have a text this is why we have to include the information from our existing document now we're able to update our entry let's try to delete an entry so this particular entry the url remains the same but instead of the patch we'll need the delete method and then let's remove the body we click on the send button and look at that entry deleted successfully so let's try to get all our entries and see if we can still find that particular entry click on the send button and it's empty so we've successfully added an entry we've successfully updated that entry we've successfully fetched that entry from the database and we've successfully deleted the entry so we're basically done with our journal rest api remember like we discussed in the course of building this application we need to add extra validation extra middleware and you can easily do that by adding whatever media you're on before the function so right here on line 8 you can add a new middleware and then add entry function so you can also use this to authenticate and authorize users but that will be in another course where we'll learn how to do authentication and authorization with firebase backend and firebase front end right now we're done with creating a rest api with firebase cloud functions and typescript we can get we can post we can updates and we can delete this has been a good ride so you can check on my youtube channel for any updated content on firebase the firebase authentication slash authorization course and we can also decide to install the firebase console locally so let's say we want to avoid to be deploying every time we make a change to a firebase application we can install the firebase console locally and you can see an information on that in the firebase documentation on how to install the firebase console locally i'll also create a video on that so you can check back in my channel to see if i've done that for now we're done and i'm really glad we took this course together and if you enjoyed this course please me favor and subscribe to my youtube channel that's youtube.com slash ebenezer i really love that all right see you in my next video
Info
Channel: Ebenezer Don
Views: 20,357
Rating: undefined out of 5
Keywords: serverless, serverless architecture, serverless computing, serverless deployment, serverless framework, serverless framework node js, serverless functions, serverless offline node js, serverless tutorial
Id: T8SZv6h2WbY
Channel Id: undefined
Length: 61min 1sec (3661 seconds)
Published: Wed Dec 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.