├── .gitignore ├── README.md └── json-placeholder.png /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FULL STACK COURSE 2023 2 | 3 | 1. [ REACT MasterClass Course Material - HERE](#react-js-masterclass) 4 | 5 | - React MasterClass 2023 [Video](https://youtu.be/6l8RWV8D-Yo) 6 | 7 | - Assignment Solutions [Video](https://youtu.be/u6zQ9yhIg4o) 8 | 9 | 2. [ NODE MasterClass Course Material - HERE](#node-js-masterclass) 10 | 11 | - NODE 2023 [Video](https://youtu.be/ChVE-JbtYbM) 12 | 13 | 3. [ Redux MasterClass Course Material - HERE](#redux-js-masterclass) 14 | 15 | - REDUX 2023 [Video](TODO) 16 | 17 | # React JS MasterClass 18 | 19 | 20 | 21 | Hi, This is course page of **CoderDost Youtube Channel** React JS 2023 Course [Video Link ](https://youtu.be/6l8RWV8D-Yo), 22 | 23 | ### How to use this code : 24 | 25 | #### You can **download code** in 2 ways : 26 | 27 | 1. **Git Commands** 28 | 29 | - use `git clone ` 30 | 31 | - checkout branch according to Chapter number `git checkout react-1` 32 | 33 | - run `npm install` inside the root directory before running the code 34 | 35 | 36 | 37 | 2. If you are not comfortable with git, directly **download the branch as Zip**. 38 | 39 | - Choose branch related to the Chapter e.g. `react-1` 40 | 41 | - run `npm install` inside the root directory before running the code 42 | 43 | 44 | 45 | 46 | # React JS Series 47 | 48 | 49 | 50 | 51 | ## Chapter 1 - Introduction to React & Setup 52 | 53 | 54 | - **Assignment 1** : If we delete `node_modules`. How to run our app again successfully ? 55 | 56 | 57 | - **Assignment 2** : How to remove double `console.logs` from React ? [ it is not needed in real life to remove them, its just an assignment problem ]. [ *Hint: Some special Component at top level is of App is causing it* ]. We explore more about - why this is needed in later videos. 58 | 59 | ### Special Assignments ============== 60 | 61 | - **Assignment 3** : Create a Page with multiple React Apps. Both React Apps should be independent of each other. 62 | 63 | - **Assignment 4** : Try to build a react app using other toolchains like `Vite` 64 | 65 | 66 | 67 | ### Related Videos : 68 | 1. De-structuring Assignment : [Long Video](https://youtu.be/sNhqFofQhFs) | [Object De-structure Short Video](https://youtube.com/shorts/H3MKXE69_c8) | [Array De-structure Short Video](https://youtube.com/shorts/ONGyMq49kZY) 69 | 2. Import/Export : [Long Video](https://youtu.be/7P5JUMc1cI4) | [Short Video](https://youtube.com/shorts/sUUOSWlwfM8) 70 | 71 | 72 | 73 | ## Chapter 2 - Components - JSX and Props 74 | 75 | 76 | - **Assignment 1** : Create a simple React app for **RESUME Builder**. It will be static website. You have to make components like **Resume** as top level and under it - **Skills**, **Education**, **Experience** etc as components. All resume data will be under 1 big JavaScript object like which you can us in components via props. You can fix the number of items in **Skills**, **Education**, **Experience** or any section. Example you can say that only 3 experience items is allowed. 77 | 78 | ```js 79 | resume = { 80 | experience : [ { year:2012, company:'xyz', role:'something' }], 81 | education:[ ], 82 | skills : [ 'react js', 'node js'] 83 | ..... 84 | ... 85 | } 86 | ``` 87 | 88 | > You can choose any simple HTML layout and convert it to React Components 89 | 90 | Example Link : [ Resume HTML ](https://codepen.io/emzarts/pen/OXzmym) 91 | 92 | ### Special Assignments ============== 93 | 94 | - **Assignment 2** : Create a Parent Component called **Border** which can provide some CSS border to any component nested into it. [Hint : You will need to use `children` props here 95 | ```jsx 96 | < Border> 97 | < Component > 98 | < Border /> 99 | ``` 100 | 101 | ### Related Videos : 102 | 1. De-structuring Assignment : [Long Video](https://youtu.be/sNhqFofQhFs) | [Object De-structure Short Video](https://youtube.com/shorts/H3MKXE69_c8) | [Array De-structure Short Video](https://youtube.com/shorts/ONGyMq49kZY) 103 | 2. Import/Export : [Long Video](https://youtu.be/7P5JUMc1cI4) | [Short Video](https://youtube.com/shorts/sUUOSWlwfM8) 104 | 3. Spread Operator : [Long Video](https://youtu.be/X4Iv0TBHDQ4) | [Short Video](https://youtube.com/shorts/5dBZGyXutx8) 105 | 106 | 107 | ## Chapter 3 - Conditional Rendering & Lists 108 | 109 | 110 | - **Assignment 1** : Make a simple component which can conditionally render a list with **number** or **alphabets** or ***bullets*** in HTML for number. e..g. use a prop like `layout` for this. Also use a prop `items` for array of items in list. 111 | ```jsx 112 | < List layout="numbered" items={items}/> 113 | < List layout="alpha" items={items}/> 114 | < List layout="bullet" items={items}/> 115 | ``` 116 | 117 | - **Assignment 2** : This is continuation of previous assignment **RESUME Builder** 118 | 1. In this part you have to make some conditional rendering. Suppose if any section doesn't exist you have to remove that section from **Resume**. Example if `skills` is empty array than don't display `skills` section in Resume. 119 | 2. You have to use `map` in most places where there are arrays. Like **Skills**, **Education**, **Experience** if there are 3 entries, use `map` to display 3 experience items. You don't need fix number of items. Any array can have 1 to 10(or some Limit) any number of items. You can put some Limit, so that your layout is not affected. 120 | 3. Conditionally put some styling to **Resume**. Like `light` theme or `dark` theme or any other way you can switch the CSS layouts. 121 | 122 | ```js 123 | resume = { 124 | experience : [ { year:2012, company:'xyz', role:'something' }], 125 | education:[ ], 126 | skills : [ 'react js', 'node js'] 127 | ..... 128 | ... 129 | } 130 | ``` 131 | 132 | > You can choose any simple HTML layout and convert it to React Components 133 | 134 | Example Link : [ Resume HTML ](https://codepen.io/emzarts/pen/OXzmym) 135 | 136 | 137 | 138 | 139 | ### Related Videos : 140 | 1. Ternary Operator : [Video](https://youtu.be/F_95TPUIA2c) 141 | 2. Logical AND (&&) : [Video](https://youtu.be/7dXLYWWTRXI) 142 | 3. Higher Order functions (map, filter, reduce) : [Video](https://youtu.be/oGpA98nNx6Y) 143 | 4. Import/Export : [Long Video](https://youtu.be/7P5JUMc1cI4) | [Short Video](https://youtube.com/shorts/sUUOSWlwfM8) 144 | 145 | 146 | ## Chapter 4 - Events && Event Bubbling 147 | 148 | 149 | - **Assignment 1** : Make a simple page with 1 Image, 1button, 1 form Input text box and try to apply these events . 150 | 151 | - Image : **onMouseOver** : when you hover on image. Image should increase in size. Think of any way where you can do it. Also, try that when you "move out" the mouse, it should be back to normal size. 152 | - Button : **onDoubleClick**: when you doubleClick a button. show some alert box. Also make a console.log for single click event. Is console.log printed twice on double click ? check this ? 153 | - Input Textbox : **onFocus**, **onBlur** are 2 events which occur when you enter or exit an input text box by click of mouse etc. Use it to display some console.log, which print "focused on the textbox", "out of textbox". 154 | - **onCopy, onCut, onPaste** are 3 events which you can use on any text value etc. try to use it on a paragraph and just alert the user that something is copied, cut or pasted. 155 | 156 | 157 | 158 | - **Assignment 2** : Make a form using `` < Form> `` tag and put an textbox and button inside this form. try to click the button after entering into textbox. Does form reloads ? Can you try to stop is using `e.preventDefault`. Try it. 159 | 160 | - **Assignment 3** : use an Input Textbox : after you enter some text. try to press **ENTER** button and show the an alert or console.log. You can capture the **onKeyPress** event, button how you will you make it work only for "Enter" ? It should not work on pressing of other keys. [*Hint: Explore the synthetic event object* ] 161 | 162 | 163 | - **Assignment 4** : This is continuation of previous assignment **RESUME Builder**. 164 | - Add a **print** button to print the current resume. You can use a DOM method ``window.print`` to print the PDF. 165 | 166 | 167 | - **Assignment 5** : Can you try the challenge of passing the function in one Prop like `onPlay` and the message inside that function to be accessed from other prop `message` [ As shown in Chapter Video ] 168 | 169 | ### Special Assignments ============== 170 | 171 | - **Assignment 6** : Using **event bubbling** concept print the name of Parents to Child of any clicked element. It should be order in "**GrandParent >Parent > Child**" this kind of order. Where "Child" represents the current clicked element. 172 | 173 | - **Assignment 7** : Make a custom event called **onClose**. this event should close the current browser tab. you can apply it to a button on click or anywhere. 174 | 175 | ### Related Videos : 176 | 177 | 1. HTML DOM Elements and manipulation [Video](https://youtu.be/kwfbaHNZ_aU) 178 | 2. HTML DOM Events and manipulation : [Video](https://youtu.be/5kpe_tg_Cis) 179 | 180 | 181 | 182 | 183 | ## Chapter 5 - State, useState Hooks 184 | 185 | - **Assignment 1** : Make a digital **CLOCK** Component using useEffect Hook. We need to only update the time Upto seconds in it. HH:MM:SS format can be used. Can you make it send a Console.log at end of every minute ? 186 | 187 | - **Assignment 2** : Implement a simple **TIMER** that displays the elapsed time since the start button was pressed, and it can be stopped and reset. Like a stopwatch. 188 | 189 | 190 | 191 | 192 | ## Chapter 6 - Form , Synthetic Event Object & Lifting State up 193 | 194 | 195 | - **Assignment 1** : Create a Dropdown (< Select >) menu which is formed by a `nations` array. You can push to this array new items using a 2 **input textbox** (for country name and code) and **button**. 196 | On selection of the any option from dropdown, its value should be displayed on console.log 197 | 198 | ``` js 199 | const nations = [ 200 | { name: 'India', value: 'IN' }, 201 | { name: 'Pak', value: 'PK' }, 202 | { name: 'Bangladesh', value: 'BG' }, 203 | ] 204 | ``` 205 | 206 | 207 | - **Assignment 2** : **FILTERED LIST** : Make a **List** of something using an Array (a list can of cricket player /countries/ movie name etc). Now make this list it searchable, you have to put a **input textbox** at top of list. When you type in **textbox** it should only show you items matching from text typed. For example - 208 | If you type only "in" it should show things like "India" / "China" as both have `in` in it. 209 | - **Assignment 2.1** : **FILTERED LIST** : Make above **List** as separate components for List, Input form and pass the states from each other using concepts learnt till now. 210 | 211 | 212 | - **Assignment 3** : 213 | 214 | This is continuation of previous assignment **RESUME Builder**. Now you have to make a separate component **ResumeEditor** which has a **FORM**. This form will have many **input boxes**. Each one related to one section. For example you can have one input box or **experience** section. Another input box for **skill** section and like this. Every input box should have an **Add** button in front of it. Once you press this add button that information is stored in the state , which you can update at top of the App level. Now this state should update the **Resume** Component and its child you have built. 215 | - first component will be your **RESUME** document which is only for reading purpose. 216 | - second component will be this **FORM** 217 | - you have to manage the state in between 218 | - only Add functionality is required in this assignment 219 | - you can change input boxes according to your need depending on your format of Resume. You can have multiple textboxes also for same section. Like for date + experience item etc. 220 | 221 | - **Assignment 4** : Try this challenge : https://beta.reactjs.org/learn/state-a-components-memory#challenges 222 | 223 | ### Related Videos : 224 | 225 | 1. HTML Forms-1 [Video](https://youtu.be/DUJEpSkzrVA) 226 | 2. HTML Forms-2 : [Video](https://youtu.be/Nj6Omw6zOok) 227 | 228 | 229 | 230 | ## MINI PROJECT 231 | 232 | 233 | # Project 1 - TODO App 234 | 235 | Todo app can be used to maintain a list of your pending daily items. A Simple todo list must have these features 236 | 237 | 238 | * You can add any new item to TODO list 239 | * You can click on any item to mark it as done, if you have done that by mistake - you can click again to undo. 240 | * You can delete any item (completed or pending) 241 | * You get a total of completed items and overall items on the list. 242 | * You can move list items "Up" or "Down" using buttons. 243 | 244 | 245 | ![Output](https://raw.githubusercontent.com/abhishekrathore/fullstackbootcamp2019/master/01_REACT/2_PROJECT_1/images/todo-project.gif) 246 | 247 | 248 | ## Additional Features 249 | 250 | **KEYBOARD BASED Features** : 251 | 252 | - use **ENTER** key on keyboard to add a new item. 253 | - when you click on an item, it should be selected (you can change style to show it is selected) 254 | - If you press the **DELETE** key on the keyboard after selecting the list item it should delete that list item. If you have not selected any item the last item should be deleted. 255 | - You can select list item and press **UP** arrow key to Move It Up. And you can press the **DOWN** key to move it down. 256 | 257 | 258 | **Other Features** : 259 | 260 | * **Pin element to Top of List** : On double click make element reach top of list. You can show a different color also to show that element is pinned. 261 | * **Show the date & time** at which list item was added. 262 | * **Order** by : Todo Item names, Date added, Completed. 263 | * **Due date feature** : Add a due date of task of any todo item. You will need to add another input box for this at top. Whenever you are in 24 hour limit of due date - Task outline will be shown in ORANGE color. e.g if a task is due on 23 May - from 22nd May it should show in ORANGE outline color. If a due date is passed task should show RED Outline. 264 | * Use some component like `https://github.com/react-component/progress` to show a **progress bar** at top of list. This progress bar will show how much of total percent of tasks are completed. 265 | * **Delete item via swipe gesture** - like swipe to right on mobile phone. [*Hint: You have to find an event type for this* ] 266 | 267 | **Advanced Features** : 268 | 269 | * **Use localStorage** in browser using libraries like `https://github.com/localForage/localForage` to make your todo list permanent in browser. This will have your list stored in browser database and will not delete it on refresh or closing of browser. 270 | [LocalStorage Video](https://youtu.be/OTkQVPVYW7w) 271 | [LocalForage Video](https://youtu.be/Rqyu9qzydoc) 272 | 273 | **ANIMATION BASED Features [optional]** : 274 | 275 | * Enter Animation : Animate list item on adding. 276 | * Exit Animation : Animate list item at removal. 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | ## Chapter 7 - More State & useEffect hooks 285 | 286 | - **Assignment 1** : The method shown in this video was just to introduce **useEffect** hook. However that was not the correct use of useEffect hook. Can you change the code to remove useEffect and still have the editVideo functionality. [ *Hint : use the concept that Component is rendered every time prop changes* ] 287 | 288 | - **Assignment 2** : This is continuation of previous assignment **RESUME Builder**. 289 | - Add functionality to **delete** the items from resume. 290 | - Add functionality to **update** the items from resume. 291 | - you have to manage the state in between 292 | - you can change input boxes according to your need depending on your format of Resume. You can have multiple textboxes also for same section. Like for date + experience item etc. 293 | - Check the output can be printed perfectly in PDF. 294 | 295 | 296 | ## Chapter 8 - useReducer 297 | 298 | - **Assignment 1** : Try this challenge : https://beta.reactjs.org/learn/extracting-state-logic-into-a-reducer#challenges 299 | 300 | - **Assignment 2** : Convert your **RESUME BUILDER** Application from `useState` to `useReducer` by converting states logic to a common reducer. Your reducer can have as many switch cases as you want. You can also divide them based on sections. `ADD_SKILL`, `ADD_EXPERIENCE` etc. to make logic even simpler for developer. 301 | 302 | ### Related Videos : 303 | 304 | 1. REDUX - Understand it in Simple way [Video](https://youtu.be/WdEQNzUMP_M) 305 | 306 | 307 | 308 | ## Chapter 9 - Context API & useContext 309 | 310 | - **Assignment 1** : Try this challenge : 311 | https://beta.reactjs.org/learn/passing-data-deeply-with-context#challenges 312 | 313 | - **Assignment 2** : Add a Context to your **RESUME BUILDER** to change font-size, font-color and some other font-properties. Also add a form to changed these property at top of App. 314 | 315 | - **Assignment 3** : Add a Context to your **RESUME BUILDER** to change Dark Mode and Light Mode. You can also use a `React Switch` kind of library to make it more user friendly to switch. 316 | 317 | 318 | ## Chapter 10 - Context API with useReducer [Redux architecture] 319 | 320 | ### Special Assignments 321 | 322 | - **Assignment 1** : Make a **useCounter** Hook: To keep track of a number that can be incremented or decremented. 323 | ```js 324 | const [count, increment, decrement] = useCounter(0); 325 | ``` 326 | 327 | 328 | ## Chapter 11 - useRef 329 | 330 | - **Assignment 1** : Try this challenge: 331 | 332 | https://beta.reactjs.org/learn/referencing-values-with-refs#challenges 333 | 334 | - **Assignment 2** : Try this challenge: 335 | https://beta.reactjs.org/learn/manipulating-the-dom-with-refs#challenges 336 | 337 | - **Assignment 3** : Make a **useWindowSize** Hook: which returns size of current browser window. 338 | ```js 339 | const [width, height] = useWindowSize(); 340 | ``` 341 | 342 | 343 | 344 | ### Related Videos : 345 | 346 | 1. Complete DOM Course playlist [Video](https://bit.ly/35nMKB7) 347 | 348 | 349 | 350 | ## Chapter 12 - useEffect and API calling 351 | 352 | - **Assignment 1** : Try this challenge : 353 | 354 | https://beta.reactjs.org/learn/synchronizing-with-effects#challenges 355 | 356 | - **Assignment 2** : Try this challenge : 357 | 358 | https://beta.reactjs.org/learn/removing-effect-dependencies#challenges 359 | 360 | - **Assignment 3** : Try this challenge : 361 | 362 | https://beta.reactjs.org/learn/reusing-logic-with-custom-hooks#challenges 363 | 364 | - **Assignment 4** Use **JSON Placeholder API** (link given below). 365 | - You have to create a button which can get some posts and show them in a List. 366 | - You have to a **show comments** button on each list item. On click of show comments, Post's comments should be fetched below that list item. [ Comments are available for each post in API] 367 | - When you click on a particular list item's show comments, it should expand and **show** comments, otherwise it should collapse and **hide** the comments. 368 | - Try to optimize by : 369 | 370 | - Only getting comments of required Post items (not all at a time) 371 | - Storing somehow the old comments of closed list items. So you will not fetch them again, when your show comments again. 372 | 373 | ![enter image description here](https://raw.githubusercontent.com/coderdost/full-stack-dev-2023/main/json-placeholder.png) 374 | 375 | ### Related Links : 376 | 377 | 1. Mockaroo fake data APIs [Link](https://www.mockaroo.com/) 378 | 2. JSON placeholder API [Link](https://jsonplaceholder.typicode.com/) 379 | 380 | 381 | 382 | ## Chapter 13 - Memoization - useMemo, useCallback, memo 383 | 384 | - **Assignment 1** : Implement a component that displays a list of items. The component should memoize the list of items to prevent unnecessary re-rendering. 385 | 386 | - **Assignment 2**: How to use memoization in the **JSON Placeholder API** assignment in previous problem. Can you try to **optimize** it using **useMemo/useCallback** ? 387 | 388 | - **Assignment 3**: **useMemo** and **useCallback** are same hook. useCallback is just a convenient hook way to write **useMemo** for functions. Prove this using **useMemo** in place of **useCallback** in any previous problem. *[ Hint : you will have to change the useMemo callback and return the function definition ]* 389 | 390 | 391 | 392 | ## Chapter 14 - Advanced React - Part 1 393 | 394 | 395 | - **Assignment 1** : 396 | Try to apply `useDeferredValue` and `useTransistion` hooks on API based components. Either make a new one or use any existing code you have from other assignments. You can use `Chrome Network throttling` from **Devtools** > **Performance** Tabs and use **Slow 3G** option to see the effects 397 | 398 | 399 | 400 | ## Chapter 15 - Advanced React - Part 2 401 | 402 | - **Assignment 1** : 403 | Try to use `window.print` functionality as show in code without flushSync and see if really make a difference. Also, try the same on `alert` functionality, can it also work ? 404 | 405 | 406 | ------ 407 | --- END OF REACT COURSE ------ 408 | 409 | ------ 410 | 411 | 412 | # Node JS MasterClass 413 | Hi, This is course page of **CoderDost Youtube Channel** 414 | NODE JS 2023 Course [Video Link](https://youtu.be/ChVE-JbtYbM) 415 | 416 | 417 | 418 | ### How to use this code : 419 | 420 | You can **download code** in 2 ways : 421 | 422 | 1. **Git Commands** 423 | 424 | - use `git clone ` 425 | 426 | - checkout branch according to Chapter number `git checkout node-1` 427 | 428 | - run `npm install` inside the root directory before running the code 429 | 430 | 431 | 2. If you are not comfortable with git, directly **download the branch as Zip**. 432 | 433 | - Choose branch related to the Chapter e.g. `node-1` 434 | 435 | - run `npm install` inside the root directory before running the code 436 | 437 | **NOTE** : Code for **React JS app** is available in final code `node-12` branch in folder `react-app`. It can be used in previous chapters also like chapter-8 etc (however it's the final code, so step-wise code is not available for React, However one can follow the tutorial and make it , sorry for inconvenience) 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | ## Chapter 1 - Introduction to Node, NPM, Package.JSON 446 | 447 | ### [[ Chapter Notes ]] 448 | 449 | - **Node JS** installation from official site nodejs.org - use only LTS versions 450 | - Use **terminal / command prompt** to check installation : 451 | ``` node -v ``` 452 | ```npm -v ``` 453 | - **VS Code** installation directly from code.visualstudio.com site 454 | - Use VS code terminal to run **commands** 455 | - **Node REPL** interface can be used directly by typing `node` in **terminal / command prompt** . Use **Ctrl+D** to exit interface. Use **CTRL+C** to exit terminal 456 | - Running any JavaScript file from node using `node filename.js` 457 | - **Modules** are basic containers in Node/JavaScript system. 1 file can be one module in Javascript. 458 | - Two type of Module Systems in node JS are - **CommonJS** module and **ES** Modules. 459 | 460 | **- CommonJS Module** 461 | ```javascript 462 | //lib.js 463 | exports.sum = function(){} 464 | 465 | //index.js 466 | const module = require('./lib.js') 467 | module.sum(); 468 | ``` 469 | **- ES Module** 470 | 471 | ```javascript 472 | //lib.js 473 | export {sum} 474 | 475 | //index.js 476 | import {sum} from './lib.js' 477 | 478 | ``` 479 | 480 | - FileSystem Module(fs) is one of core modules of Node JS. **fs** can be used to read/write any file. There are many more core modules in NodeJS which you can check in NodeJS API docs. 481 | - Reading files can be **Synchronous** or **Asynchronous**. **Async** is most preferred method in NodeJS. As there is **NO blocking of I/O in NodeJS** 482 | 483 | - Node project can be initialized with `npm init` command which also creates `package.json` file 484 | - **package.json** is a configuration file for node projects which has **scripts**, **dependencies**, **devDependencies** etc 485 | - `npm install ` is used to install any online modules available for node on NPM repository online. 486 | - `nodemon` is a package for running node server and track live changes to re-start again. 487 | - `scripts` inside **package.json** can be used like `npm run ` e.g `npm run dev`. Only for `npm start` you can avoid `run`. 488 | - use `npm install -g ` to install packages globally on your system. Not just in the project but useful all over your system. 489 | - Node versions are formatted like **4.1.9** where these are `major.minor.patch` versions. 490 | - you can install all dependencies again using `npm install` again 491 | - **package-lock.json** has exact versions installed and link of dependencies of each package. 492 | - use `npm update` to update packages safely. `npm outdated` shows outdated and latets versions of packages installed in your **package.json** 493 | - use `npm uninstall ` to uninstall packages from `package.json` 494 | - `node_modules` should not be shared - you can make `.gitignore`to ignore them to be uploaded. 495 | 496 | 497 | 498 | ### [[ Assignments ]] 499 | 500 | - **Assignment 1** : If we delete `node_modules`. How to run our application again successfully ? 501 | - **Assignment 2** : How to use command line arguments in Node JS. Like `node index.js 3 2` - how can I get 3 and 2 to be used in my programs. [ *Hint : search for command line arguments in node* ] 502 | - **Assignment 3** : Explore the `os` module in Node Js from their documentation. What all info you can access from it about your operating system ? 503 | - **Assignment 4** : Explore about **Asynchronous** nature of JS as a single threaded language and how it is achieved using **Event Loop**. Video are given below in related videos sections. 504 | - **Assignment 5 [Challenge]** : Can you run a system command from Node JS javascript file e.g. `ls` `dir` commands ? and can you store its output in a text file ? 505 | 506 | 507 | ### Related Links/Videos 508 | 509 | 1. [Callbacks](https://youtu.be/rx-y7U4x4wc) 510 | 2. [Promises](https://youtu.be/aA4-VNZK2s0) 511 | 3. [Async Await](https://youtu.be/rdy8ZV0LXV0) 512 | 4. [Import/ Export example](https://youtu.be/7P5JUMc1cI4) 513 | 5. [Event Loop in Node JS](https://youtu.be/W-HQC_YUGBY) 514 | 515 | 516 | 517 | ## Chapter 2 - Server Concepts with Node - http module 518 | 519 | ### [[ Chapter Notes ]] 520 | 521 | #### HTTP requests 522 | 523 | Request object comprises of many properties, but important ones are : 524 | 525 | - **Type of Request** : GET, POST, PUT, DELETE etc. 526 | - **Headers** : Meta data sent by your browser like browser name, cookies, authentication information etc. 527 | - **Query Parameters** (url?`name=john`) : This is used in GET requests to send data to server 528 | - **Route Params** (url/`john`) 529 | - **Body data** : This is used in POST and other requests to send data to server 530 | 531 | #### HTTP responses 532 | 533 | Response object comprises of many properties, but important ones are : 534 | 535 | - **Headers** : Meta data sent by your server back to client like server name, content size, last updated time etc. 536 | - **Response status code** (`200`, `404`, `403`, `502`) 537 | - **Response body** : Actual data to be sent to client : HTML, JS, JSON, CSS, Image etc. 538 | 539 | #### More info 540 | 541 | - HTTP requests and responses can be tracked from **Dev Tools** > **Network Tab** 542 | - In Node, we can use core **http** module to create a Server which listens to requests, modify data in-between and provides responses. Server needs a **PORT** to be bound to - use only port number > 1024. 543 | - Server can simply be said as **a function which receives a request and returns a response**. [ This is just for understanding] 544 | - There are many **Headers** which exists on request and responses - shared a link below with list of existing headers. 545 | 546 | - We can use Server to do 3 things: 547 | - **Static file Hosting** : Sending normal files without formatting or modifying. 548 | - **Server Side Rendering** : Mixing data with templates and rendering dynamic views (dynamic web pages) 549 | - **Web APIs** : Sending data via some APIs/ endpoints. 550 | 551 | - Every Request has one and only one response. If there is more than 1 response which you want to send - you will encounter a error - "*Headers already sent*" 552 | - POSTMAN is a software for doing complex API requests. 553 | 554 | ### [[ Assignments ]] 555 | 556 | - **Assignment 1** : Capture the request which goes when you like a post on facebook (using Chrome network). What are the headers ? What is the payload ? 557 | - **Assignment 2** : In the chapter we developed a server with only URL switch, but you have to make that more efficient by making it check both METHOD (GET,POST) + URL path 558 | - So output of a request with **GET /demo** will be different from **POST /demo** [ Use POSTMAN for requests] 559 | - **Assignment 3 [Challenge]** : Try and run 2 different server using the same code you have `index.js`. You will need to use 2 different ports. But can you do it using the same file and changing PORTS dynamically somehow ? 560 | - **Assignment 4 [Challenge]** : You can also send some data to server using /demo?product=123. where product=123 is called **query parameters**. Can you capture that data and make the product page work according to the ID (123) . [ This we will do in next chapters using express, but you can give it a try ] 561 | 562 | 563 | ### Related Links/Videos 564 | 565 | 1. [Web Server Concepts in 1 Video](https://youtu.be/sfMNI0yLZII) 566 | 2. [List of HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) 567 | 3. [List of HTTP methods](https://www.restapitutorial.com/lessons/httpmethods.html) 568 | 4. [dummy JSON site](https://dummyjson.com/) 569 | 570 | 571 | ## Chapter 3 - Express JS 572 | 573 | ### [[ Chapter Notes ]] 574 | 575 | - **ExpressJS** is *de-facto* Node framework - and used in most Node applications which are used as web server. 576 | - You can install express `npm install express` 577 | - Express has few level of methods : 578 | - Application methods : e.g. app.use() 579 | - Request methods 580 | - Response methods 581 | - Middleware methods 582 | - Router methods 583 | 584 | - **Response** methods (**res** is our response objects) 585 | - **res.send()** - for sending HTML 586 | - **res.sendFile(**) - for sending File 587 | - **res.json** - for sending JSON 588 | - **res.sendStatus(404)** - for sending HTTP status only 589 | 590 | - **HTTP Request** Types we generally use : 591 | - GET 592 | - POST 593 | - PUT 594 | - DELETE 595 | - PATCH 596 | - API / Endpoints / Routes are used inter-changeably but they are related to server paths. 597 | 598 | - **Middle-ware** : Modifies the request before it reaches the next middleware or endpoints. 599 | - Sequence of middleware is very important, as first middleware is first traversed by request. 600 | - Middle-wares can be used for many use cases, like loggers, authentication, parsing data etc. 601 | - Middle-ware can be : 602 | - Application level : server.use(**middleware**) 603 | - Router level : server.get('/', **middleware**, (req,res)=>{}) 604 | - Built-in middleware : **express.json()** [ for parsing body data], **express.static()**[for static hosting] 605 | - External Middle-wares - like **morgan** 606 | 607 | - **Request** properties (**req** is our request object) 608 | - **req.ip** - IP address of client 609 | - **req.method** - HTTP method of request 610 | - **req.hostname** - like google.com / localhost 611 | - **req.query** - for capturing query parameters from URL e.g. localhost:8080 ? **query=value** 612 | - **req.body** -for capturing request body data (but its needs a middleware for body data decoding) 613 | - **req.params** - for capturing URL parameters for route path like `/products/:id` 614 | 615 | - **Static Hosting** : we can make 1 or more folders as static hosted using **express.static** middleware. 616 | `server.use(express.static(< directory >))` 617 | Static hosting is like sharing a folder/directory and making its file readable as it is. 618 | Note : `index.html` is default file which would be read in a static hosted folder, if you don't mention any file name. 619 | 620 | 3 major ways of sending data from client to server via request are : 621 | 622 | **1. Send data via URL in Query String** 623 | 624 | This is easiest method to send data and mostly used in GET request. 625 | 626 | When you have URL with `?name=Youstart&subject=express` at end, it translates in a query string. In query string each key,value pair is separated by `=` and between 2 such pairs we put `&`. 627 | 628 | To read such data in express you can use `req.query` : 629 | ```javascript 630 | server.get("/demo",function(req,res){ 631 | console.log(req.query) // prints all data in request object 632 | res.send(req.query); // send back same data in response object 633 | }) 634 | ``` 635 | 636 | - **Assignment 1** : 637 | 638 | Make above server with API endpoint `/demo` as shown above : 639 | 640 | 1. Try to call this API in your browser `http://localhost:8080/demo?name=Youstart` - this will return a response of `req.query` JSON object 641 | 642 | 2. Create 3 query parameters `name`, `age`, `subject` with some values. Check the final output of `req.query` - can you find all data on server side. Can you send it back to client via `res` object. 643 | 644 | 645 | **2. Send data via Request Params** 646 | 647 | In this method you can have a URL with url path like `/Youstart/express` at end it translates in a param string. In param part string each value is separated by `/`. As you can see that URL only contains `value` not the `key` part of data. `key` part is decided by the endpoint definition at express server 648 | 649 | server.get("/demo/:name/:subject",function(req,res){ 650 | console.log(req.params) // prints all data in request object 651 | res.send(req.query); // send back same data in response object 652 | }) 653 | 654 | So sequence of values matter in this case. As values sent from client are matched with `name` and `subject` params of URL later. 655 | 656 | - **Assignment 2** : 657 | 658 | Make above server with API endpoint `/demo` as shown above : 659 | 660 | 1. Try to call this API in your browser `http://localhost:8080/demo/Youstart/Express` - this will return a response of `req.params` JSON object 661 | 662 | 2. Create 3 URL params `name`, `age`, `subject` . Call the URL and check the final output of `req.params` - can you find all data on server side. Can you send it back to client via `res` object. 663 | 664 | 665 | **3. Send data via Request Body** 666 | 667 | Final method of sending data is via body part of request. We can send data directly to body using URL. We have to either use one of these methods 668 | 669 | 1. Use a HTML Form and make `method` value as `POST`. This will make all name=value pair to go via body of request. 670 | 671 | 2. Use special browsers like POSTMAN to change the body directly. (We will see this example in next classes) 672 | 673 | ```js 674 | server.post("/demo",function(req,res){ 675 | console.log(req.body) // prints all data in request object 676 | res.send(req.body); // send back same data in response object 677 | }) 678 | ``` 679 | 680 | 681 | ### Related Links/Videos 682 | 683 | 1. [Middleware Explanation video](https://www.youtube.com/watch?v=qkMJL0FwiyE) 684 | 2. [List of useful 3rd party middleware for Express](https://expressjs.com/en/resources/middleware.html) 685 | 3. [List of HTTP response status](https://www.restapitutorial.com/httpstatuscodes.html) 686 | 687 | 688 | 689 | ## Chapter 4 - REST API using Express JS 690 | 691 | ### [[ Reading Material ]] 692 | 693 | #### HTTP Methods 694 | 695 | The HTTP method is the type of request you send to the server. You can choose from these five types below: 696 | 697 | - `GET` : This request is used to get a resource from a server. If you perform a `GET` request, the server looks for the data you requested and sends it back to you. In other words, a `GET` request performs a `READ` operation. This is the default request method. 698 | 699 | - `POST` This request is used to create a new resource on a server. If you perform a `POST` request, the server creates a new entry in the database and tells you whether the creation is successful. In other words, a `POST` request performs an `CREATE` operation. 700 | 701 | - `PUT` and `PATCH`: These two requests are used to update a resource on a server. If you perform a `PUT` or `PATCH` request, the server updates an entry in the database and tells you whether the update is successful. In other words, a `PUT` or `PATCH` request performs an `UPDATE` operation. 702 | 703 | - `DELETE` : This request is used to delete a resource from a server. If you perform a `DELETE` request, the server deletes an entry in the database and tells you whether the deletion is successful. In other words, a `DELETE` request performs a `DELETE` operation. 704 | 705 | 706 | **REST API** are a combination of METHODS( GET, POST etc) , PATH (based on resource name) 707 | 708 | Suppose you have a resource named `task`, Here is the example of 5 REST APIs commonly available for task. 709 | 710 | 1. **READ APIs :** 711 | 712 | - GET `\tasks` : to read all 713 | 714 | - GET `\task\:id` : to read a particular task which can be identified by unique `id` 715 | 716 | 717 | 2. **CREATE APIs :** 718 | 719 | - POST `\tasks` : to create a new task object (data will go inside request body) 720 | 721 | 3. **UPDATE APIs :** 722 | 723 | - PUT `\task\:id` : to update a particular task which can be identified by unique `id`. Data to be updated will be sent in the request body. Document data will be generally **totally replaced.** 724 | - PATCH `\task\:id` : to update a particular task which can be identified by unique `id`. Data to be updated will be sent in the request body. Only few fields will be replace which are sent in **request body** 725 | 726 | 4. **DELETE APIs** : 727 | 728 | - DELETE `\task\:id` : to delete a particular task which can be identified by unique `id`. 729 | 730 | ### [[ Chapter Notes ]] 731 | 732 | - **REST API** is a standard for making APIs. 733 | - We have to consider a resource which we want to access - like **Product** 734 | - We access **Product** using combination of HTTP method and URL style 735 | 736 | **REST API ( CRUD - Create , Read , Update, Delete) :** 737 | 738 | - **CREATE** 739 | - **POST** /products - create a new resource (product) 740 | 741 | - **READ** 742 | - **GET** /products - read many resources (products) 743 | - **GET** /products/:id - read one specific resource (product) 744 | 745 | - **UPDATE** 746 | - **PUT** /products/:id - update by replacing all content of specific resource (product). 747 | - **PATCH** /products/:id - update by only setting content from body of request and not replacing other parts of specific resource (product). 748 | 749 | - **DELETE** 750 | - **DELETE** /products/:id - delete a specific resource (product). 751 | 752 | 753 | 754 | 755 | ### [[ Assignments ]] 756 | 757 | - **Assignment 1** : Make an API similar to explained above for `Quotes` take dummy data from same site ([dummy json quotes](https://dummyjson.com/quotes)) 758 | 759 | 760 | ### Related Links/Videos 761 | 762 | 1. [Middleware Explanation video](https://www.youtube.com/watch?v=qkMJL0FwiyE) 763 | 764 | 765 | 766 | ## Chapter 5 - Backend Directory Structure / MVC / Router 767 | 768 | ### [[ Chapter Notes ]] 769 | 770 | MVC (Model-View-Controller) is **a pattern in software design commonly used to implement user interfaces (VIEW), data (MODEL), and controlling logic (CONTROLLER)**. It emphasizes a separation between the software's business logic and display. 771 | 772 | In Our Project this will be : 773 | **Model** - Database Schema's and Business logics and rules 774 | **View** - Server Side Templates (or React front-end) 775 | **Controller** - functions attached to routes for modifying request and sending responses. It's a link between the Model and View. 776 | 777 | **Router** 778 | - These are like mini-application on which you can make set of Routes independently. 779 | - Routers can be attached to main Server App using `server.use(router)` 780 | 781 | Arrange Directory in Server like this : 782 | 783 | **Controllers** - file containing functions which are attached to each route path 784 | **Routes** - files containing routers 785 | **Models** : to be discussed in later chapters 786 | **Views**: to be discussed in later chapters 787 | 788 | ### [[ Assignments ]] 789 | 790 | - **Assignment 1** : Read More about Model View Controller online, link given below. 791 | 792 | ### Related Links/Videos 793 | 794 | 1. [Model View Controller](https://www.freecodecamp.org/news/the-model-view-controller-pattern-mvc-architecture-and-frameworks-explained/) 795 | 796 | 797 | 798 | ## Chapter 6 - MongoDB - Server / Mongo Shell (CLI) / Mongo Atlas 799 | 800 | ### [[ Reading Material]] 801 | 802 | MongoDB is **NoSQL** database which has a JSON like (BSON data) data storage. 803 | 804 | ## Setting up Database Server and Connecting with Mongo Shell 805 | 806 | After installing MongoDB community server package on your system - you will have to start the database server using command : 807 | 808 | ```bash 809 | mongod 810 | ``` 811 | 812 | This will start MongoDB server on default port 27017. You might have to create a directory for storage in MongoDB - if server asks for storage directory 813 | 814 | Once server is started - you can use `mongo` client to connect to local server 815 | 816 | ```bash 817 | mongo 818 | ``` 819 | 820 | Now you can use several commands to work with database: 821 | 822 | ``` 823 | show dbs 824 | ``` 825 | 826 | This will list all the database in your system 827 | 828 | ``` 829 | use 830 | ``` 831 | 832 | This will command will let you switch to a particular 833 | 834 | ## Understanding MongoDB structure 835 | 836 | 1. Hostname 837 | 2. Database 838 | 3. Collection 839 | 4. Document 840 | 841 | Hostname is Database server address - like `localhost` or `db.xy.com`. In mongoDB hostname generally uses mongodb protocol to connect. 842 | So URLs are generally are of shape : `mongodb://localhost:27017` 843 | 844 | Database are topmost storage level of your data - mostly each application has 1 database - however complex application might have more than 1 databases. Database is something like `university database` 845 | 846 | There can be many collections inside a database - collection is a group of documents of similar kind - `students`, `teachers`, `courses` etc 847 | 848 | Finally document is basic entity of storage in Mongod, it looks very similar to an object in JSON. (However it is BSON) 849 | 850 | 851 | ## MONGO CLI 852 | 853 | 854 | Mongo DB community server comes with in-bulit Mongo CLI which can act as a terminal based client. You can use the CRUD functionality from here 855 | 856 | Read the commands [here](https://docs.mongodb.com/manual/reference/mongo-shell/) 857 | 858 | #### Assignment 1 859 | 860 | * Try these commands given in Mongo CLI reference docs. 861 | 1. Show database 862 | 2. Use database 863 | 3. Show collection 864 | 4. Create Query (insertOne, insertMany) 865 | 5. Read Query (find, findOne) 866 | 6. Update Query (updateOne) 867 | 7. Delete Query (deleteOne, deleteMany) 868 | 8. Delete database (drop) 869 | 870 | #### Assignment 2 871 | 872 | #### Mongodump and Mongorestore 873 | 874 | These utilities comes with community server and can be found in CMD/terminal. They are not the part of Mongo CLI client. 875 | 876 | 1. Mongodump command is used to take backup of complete database or some collections 877 | 878 | ```bash 879 | mongodump --db accounts 880 | ``` 881 | Above command takes backup of database `accounts` and stores into a directory named `dump` 882 | 883 | 2. Mongorestore command is used to restore database 884 | 885 | ```bash 886 | 887 | mongorestore --db accounts dump/accounts 888 | 889 | ``` 890 | 891 | Above command restore your database `accounts` from backup directory `dump` 892 | 893 | 894 | 895 | **Task** : Use these commands on terminal/CMD (not inside mongo client) 896 | 897 | 1. Take a backup of database you created in assignment 1. 898 | 899 | 2. Restore the backup of database from `dump` directory. 900 | 901 | 902 | 903 | 904 | #### Using MONGODB NODE.JS DRIVER [ OPTIONAL READING - as we will not use Mongo Driver ] 905 | 906 | To install MONGODB NODE.JS DRIVER use this command 907 | 908 | ```javascript 909 | npm install mongodb 910 | ``` 911 | 912 | You can setup database in Node server using following commands : 913 | 914 | ```javascript 915 | 916 | const MongoClient = require('mongodb').MongoClient; 917 | const assert = require('assert'); 918 | 919 | // Connection URL 920 | const url = 'mongodb://localhost:27017'; 921 | 922 | // Database Name 923 | const dbName = 'myproject'; 924 | 925 | // Use connect method to connect to the Server 926 | MongoClient.connect(url, function(err, client) { 927 | assert.equal(null, err); 928 | console.log("Connected correctly to server"); 929 | 930 | const db = client.db(dbName); 931 | 932 | }); 933 | ``` 934 | 935 | Now this `db` handle can be used to perform any CRUD operation using MongoDB NodeJS driver. 936 | 937 | #### CRUD Functions links 938 | 939 | 1. Create - [Shell Version](https://docs.mongodb.com/manual/crud/#create-operations) / [Node Version](http://mongodb.github.io/node-mongodb-native/3.0/tutorials/crud#insert-documents) 940 | 2. Read - [Shell Version](https://docs.mongodb.com/manual/crud/#read-operations) / [Node Version](http://mongodb.github.io/node-mongodb-native/3.0/tutorials/crud#findoneandupdate-findoneanddelete-and-findoneandreplace) 941 | 3. Update - [Shell Version](https://docs.mongodb.com/manual/crud/#update-operations) / [Node Version](http://mongodb.github.io/node-mongodb-native/3.0/tutorials/crud#updating-documents) 942 | 4. Delete - [Shell Version](https://docs.mongodb.com/manual/crud/#delete-operations) / [Node Version](http://mongodb.github.io/node-mongodb-native/3.0/tutorials/crud#removing-documents) 943 | 944 | 945 | 946 | 947 | ### [[ Chapter Notes ]] 948 | 949 | **Mongo Server** 950 | - You can install **MongoDB community server** for your system and set the **Path** to `bin` folder 951 | - You can choose your own database path while starting the **mongod** server 952 | ``` 953 | mongod --dbpath 954 | ``` 955 | 956 | **Mongo Compass** : UI Client to see mongo server (local or remote) 957 | 958 | **Mongo Shell** : Command-line based mongo client for checking mongo database. 959 | 960 | Some Mongo Commands: 961 | 962 | ### Top Level commands : 963 | (run from anywhere inside the shell) 964 | - show dbs; 965 | - use < database-name > - to choose a database and go inside its prompt 966 | 967 | ### Database CRUD commands : 968 | (run only from inside a database) 969 | 970 | #### CREATE COMMANDS 971 | - db.< collectionName >.insertOne( *newDocument* ) 972 | - db.< collectionName >.insertMany( *documentArray* ) 973 | 974 | #### READ COMMANDS 975 | - db.< collectionName >.**find**( *filterObject* ) - to read all docs 976 | - db.< collectionName >.**findOne**( *filterObject* ) - to read one document 977 | - db.< collectionName >.**countDocuments**( *filterObject* ) - shows total number of documents. 978 | 979 | **filter** Object : *{ fieldName : {operator: value}}* 980 | fieldName : database fields name 981 | **operator** : $eq = equal , $gt= greater than, $lt : less than, $gte = greater than equal, $and and $or operator 982 | **value** : what value we are comparing with operator. 983 | 984 | e.g { age : {$gt:5}}. - **age** is **greater than** value **5** 985 | 986 | **Cursor functions :** 987 | These are applied to find() query . 988 | - **sort**( {fieldName: 1}) : 1 for ascending -1 for descending 989 | - **limit**( x ) : only gives x documents 990 | 991 | #### UPDATE COMMANDS 992 | 993 | - db.< collectionName >.**updateOne**( *filterObject*, *updateObject*, options ) 994 | - update Objects = *{ $set : {field: value}}* 995 | - options : *{upsert: true}* 996 | 997 | **Upsert** : Update + Insert, when we want a new info to create a new obejcts if no existing object matches filter queries. 998 | 999 | - db.< collectionName >.**replaceOne**( *filterObject*, *updateObject* ) 1000 | Overwrites other fields also which are not in updateObject. 1001 | 1002 | #### DELETE COMMANDS 1003 | 1004 | - db.< collectionName >.**deleteOne**( *filterObject* ) 1005 | 1006 | 1007 | **Projection** 1008 | - Only return selected fields while returning result documents. 1009 | - db.< collectionName >.find( *filterObject*, projectionObject ) 1010 | e.g. {name:1, age:1, id:0} - only show **name** and **age** and don't show **id** 1011 | 1012 | **MONGO ATLAS CLOUD SETUP** : Check the video in tutorial 1013 | 1014 | ** Enviroment Variable** : To use environment variable we can use a npm package called **dotenv** which will create new **process.env** variables. 1015 | - Install `dotenv` using `npm install dotenv` 1016 | - just have use `.env` file in your root directory 1017 | - and call `require('dotenv').config()` 1018 | 1019 | 1020 | ### Related Links/Videos 1021 | 1022 | [Mongo Atlas Setup Detailed Video](https://youtu.be/4vtFY_ijpKs) 1023 | 1024 | 1025 | ## Chapter 7 - Mongoose and REST APIs 1026 | 1027 | ### [[ Reading Material ]] 1028 | 1029 | 1030 | You can install mongoose using npm : 1031 | 1032 | ```bash 1033 | npm install mongoose 1034 | ``` 1035 | 1036 | After installing , you can import mongoose to your project : 1037 | 1038 | ```js 1039 | const mongoose = require("mongoose"); 1040 | ``` 1041 | 1042 | #### Connection to Database 1043 | 1044 | To connect mongoose to your database `test`, you have to use the following commands : 1045 | 1046 | ```js 1047 | 1048 | var mongoose = require('mongoose'); 1049 | await mongoose.connect('mongodb://127.0.0.1:27017/test'); 1050 | ``` 1051 | 1052 | Connection can also be stored in a variable to check whether it is connected properly or not. Also to disconnect database later on. You can read more details [Here](https://mongoosejs.com/docs/connections.html) 1053 | 1054 | #### Schema 1055 | 1056 | Schema is the specification according to which data object is created in Database. 1057 | 1058 | `taskSchema` which contains `title`, `status`, `date` fields. So every task object saved in database will have these 3 fields according to Schema given 1059 | 1060 | 1061 | ```js 1062 | 1063 | const mongoose = require('mongoose'); 1064 | const Schema = mongoose.Schema; 1065 | 1066 | const taskSchema = new Schema({ 1067 | title: String, 1068 | status: Boolean, 1069 | date: { type: Date, default: Date.now } 1070 | }); 1071 | ``` 1072 | 1073 | Many types of data are allowed in Mongoose Schema. The common SchemaTypes are: 1074 | 1075 | * String 1076 | * Number 1077 | * Date 1078 | * Boolean 1079 | * Mixed 1080 | * ObjectId 1081 | * Array 1082 | 1083 | You can put a lot of conditions inside the Schema object : 1084 | 1085 | ```js 1086 | 1087 | age: { type: Number, default:18, min: 18, max: 65, required :true } 1088 | // default value of Number is 18 and should be between 18-65, and can't be null or empty 1089 | 1090 | ``` 1091 | 1092 | Detailed information on SchemaTypes is [Here](https://mongoosejs.com/docs/schematypes.html) 1093 | 1094 | #### Model 1095 | 1096 | Model are similar to classes, they create a Class from Schema. These classes(i.e Models) can be used to create each new database object. 1097 | 1098 | 1099 | ```js 1100 | const mongoose = require('mongoose'); 1101 | const { Schema } = mongoose; 1102 | 1103 | const taskSchema = new Schema({ 1104 | title: String, 1105 | status: Boolean, 1106 | date: { type: Date, default: Date.now }, 1107 | }); 1108 | 1109 | const Task = mongoose.model('Task', taskSchema); //Task Model to create new database objects for `tasks` Collection 1110 | 1111 | 1112 | ``` 1113 | 1114 | #### Task 1 1115 | 1116 | Connect mongoose to a database named `todolist` if you don't have a database with this name. Mongoose will create it after you perform any insert operation. 1117 | 1118 | Creata a Schema named `taskSchema` and model named `Task` as shown above. 1119 | 1120 | 1121 | ### CRUD in Mongoose 1122 | 1123 | ### Create - new objects 1124 | 1125 | To Create new obejct in database we can use `new` keyword and create an object from Model. We can use `save()` function to save the object in database. Unless, you call save function - the object remains in memory. If your collection not yet created in MongoDB, it will created with name of Model pluralized (e.g Task will make a collection named `tasks`) 1126 | 1127 | 1128 | ```js 1129 | 1130 | server.post("/task",function(req,res){ 1131 | let task = new Task(); 1132 | 1133 | task.title = "shopping"; 1134 | task.status = true; 1135 | task.date = new Date(); 1136 | 1137 | task.save(); 1138 | }) 1139 | 1140 | ``` 1141 | 1142 | #### Task 2 1143 | 1144 | You have to create an API Endpoint to type `POST` named `/task`. It will create a new task item in database whenever called properly. All 3 fields `title`, `status`, `date` must be mandatory (`required`). If someone is not passing all fields properly, no database entry should be created. 1145 | 1146 | ```js 1147 | //request body : 1148 | 1149 | { 1150 | "title" : "task1", 1151 | "status" : true, 1152 | "date" :'2010-05-30" 1153 | 1154 | } 1155 | 1156 | // response body should return the newly created object. 1157 | 1158 | res.json(task); 1159 | 1160 | ``` 1161 | 1162 | Check using Mongo Compass/or Mongo Shell that new record in database is created. Also check name of collection. Is is `tasks` ? 1163 | 1164 | 1165 | ### Read objects 1166 | 1167 | To read new obejcts from database, one can use `find` query or similar queries. `find` queries also contain some conditions which can restrict what kind of data objects you want to read from database. 1168 | 1169 | 1170 | ```js 1171 | 1172 | server.get("/task/:name",function(req,res){ 1173 | Task.findOne({name:req.params.name},function(err,doc){ 1174 | console.log(doc) // this will contain db object 1175 | }) 1176 | }) 1177 | 1178 | 1179 | server.get("/tasks",function(req,res){ 1180 | Task.find({},function(err,docs){ 1181 | console.log(docs) // this is an array which contains all task objects 1182 | }) 1183 | }) 1184 | 1185 | 1186 | ``` 1187 | #### Task 3 1188 | 1189 | You have to create an API Endpoint to type `GET` named `/tasks`. It will return all task available in collection `tasks`. 1190 | 1191 | ```js 1192 | //request is GET so no data in body : 1193 | 1194 | 1195 | // response body should return the all db objects of collection tasks. 1196 | 1197 | res.json(tasks); 1198 | 1199 | ``` 1200 | 1201 | Check Mongo Compass/or Mongo Shell - if all records are returned in response. How you will change this API to make it return only one database record in which `title` is matched with `title` sent in request `query`. 1202 | 1203 | 1204 | 1205 | ### Update - existing objects 1206 | 1207 | To Update an existing object in database we need to first find an object from database and then update in database. This might be considered as a combination of `find` and `save` methods. 1208 | 1209 | 1210 | There are generally 2 cases in update : 1211 | 1212 | 1. Updating all values and overwriting the object properties completely. 1213 | 2. Updating only few values by setting their new values. 1214 | 1215 | 1216 | First scenario is covered using this query. Here you are overwriting all properties and resulting object will only have `name` property. 1217 | 1218 | ```js 1219 | 1220 | server.put("/task/:name",function(req,res){ 1221 | Task.findOneAndReplace({name:req.params.name},{name:'YouStart'},{new:true},function(err,doc){ 1222 | console.log(doc) // this will contain new db object 1223 | }) 1224 | }) 1225 | 1226 | ``` 1227 | 1228 | Second scenario is covered using this query. Here you are only changing value of `name` property in existing object without changing other values in Object. 1229 | 1230 | ```js 1231 | 1232 | server.put("/task/:name",function(req,res){ 1233 | Task.findOneAndUpdate({name:req.params.name},{name:'YouStart'},,{new:true},function(err,doc){ 1234 | console.log(doc) // this will contain db object 1235 | }) 1236 | }) 1237 | 1238 | ``` 1239 | 1240 | #### Task 4 1241 | 1242 | You have to create an API Endpoint to type `PUT` named `/task/:id`. It will update existing task item in database which has ObjectId set to `id` you have passed. 1243 | 1244 | ```js 1245 | //request params will have id in URL path : 1246 | 1247 | { 1248 | "title" : "task-changed", 1249 | } 1250 | 1251 | // response body should return the newly updated object. 1252 | 1253 | res.json(task); 1254 | 1255 | ``` 1256 | 1257 | Check using Mongo Compass/or Mongo Shell that only `title` of record in database is changed. All other properties remain the same. 1258 | 1259 | 1260 | 1261 | ### Delete - existing objects 1262 | 1263 | To Delete existing object from database we need to first find an object from database and then delete. This might be considered as a combination of `find` and `delete` methods. 1264 | 1265 | 1266 | ```js 1267 | 1268 | server.delete("/task/:name",function(req,res){ 1269 | Task.findOneAndDelete({name:req.params.name},function(err,doc){ 1270 | console.log(doc) // this will contain deleted object object 1271 | }) 1272 | }) 1273 | 1274 | ``` 1275 | 1276 | #### Task 5 1277 | 1278 | You have to create an API Endpoint to type `DELETE` named `/task/:id`. It will delete existing task item in database which has ObjectId set to `id` you have passed. 1279 | 1280 | ```js 1281 | //request params will have id in URL path : 1282 | 1283 | // response body should return the deleted object. 1284 | 1285 | res.json(task); 1286 | 1287 | ``` 1288 | 1289 | Check using Mongo Compass/or Mongo Shell that the record is deleted or not. 1290 | 1291 | 1292 | 1293 | 1294 | ### [[ Chapter Notes ]] 1295 | 1296 | - install mongoose 1297 | `npm install mongoose` 1298 | - Mongoose connection code 1299 | ```javascript 1300 | main().catch(err => console.log(err)); 1301 | 1302 | async function main() { 1303 | await mongoose.connect('mongodb://127.0.0.1:27017/test'); 1304 | 1305 | // use `await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test');` if your database has auth enabled 1306 | } 1307 | ``` 1308 | - Mongoose **Schema** : Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. 1309 | 1310 | ```javascript 1311 | const productSchema = new Schema({ 1312 | 1313 | title: {type: String, required: true, unique: true} , 1314 | description: String, 1315 | price: {type: Number, min:[0,'wrong price'],required: true}, 1316 | discountPercentage: {type: Number, min:[0,'wrong min discount'], max:[50,'wrong max discount']}, 1317 | rating: {type: Number, min:[0,'wrong min rating'], max:[5,'wrong max rating']}, 1318 | brand: {type: String,required: true}, 1319 | category: {type: String, required: true}, 1320 | thumbnail: {type: String, required: true}, 1321 | images: [ String ] 1322 | 1323 | }); 1324 | ``` 1325 | 1326 | - Mongoose **Model** : model are built using a combination of Schema and name of Collection. 1327 | ```javascript 1328 | const Product = mongoose.model('Product', productSchema); 1329 | ``` 1330 | 1331 | - Mongoose **Document** - its is instance of a model. so Model is like a class and documents are like its objects. These documents are directly saved in mongoDB. 1332 | ```javascript 1333 | const document = new Product(); 1334 | // document is actually saved in database after save() 1335 | await document.save(); 1336 | ``` 1337 | 1338 | Mongoose Schema/Model can act as **Model** of **Model**-View-Controller concept. 1339 | 1340 | ### CRUD API and mongoose methods 1341 | 1342 | **CREATE** : 1343 | 1. **create product** - use **POST ** HTTP Method 1344 | 1345 | ```javascript 1346 | const product = new Product(); 1347 | await product.save() 1348 | ``` 1349 | 1350 | **READ** : 1351 | 1352 | 1. **read all products** - use **GET** HTTP Method 1353 | ```javascript 1354 | const products = await Product.find(); 1355 | 1356 | const products = await Product.find({price:{$gt:500}}); 1357 | ``` 1358 | 2. **read 1 product** - use **GET** HTTP Method 1359 | ```javascript 1360 | const product = await Product.findById(id); 1361 | ``` 1362 | 1363 | **UPDATE** : 1364 | 1365 | 1. replace product fields (all fields) - use **PUT** HTTP Method 1366 | ```javascript 1367 | const doc = await Product.findOneAndReplace({_id:id},req.body,{new:true}) 1368 | ``` 1369 | 1370 | 2. update only some product fields - use **PATCH** HTTP Method 1371 | 1372 | ```javascript 1373 | const doc = await Product.findOneAndUpdate({_id:id},req.body,{new:true}) 1374 | ``` 1375 | 1376 | 1377 | **DELETE** : 1378 | 1. delete 1 product - use **DELETE** HTTP Method 1379 | ```javascript 1380 | const doc = await Product.findOneAndDelete({_id:id}) 1381 | ``` 1382 | 1383 | ### [[ Assignments ]] 1384 | 1385 | - **Assignment 1** : Make a Schema for `user` with `userSchema` which has these conditions : 1386 | - `firstName` is required, maximum length 16 chars 1387 | - `lastName` is not required, maximum length 16 chars 1388 | - `age` is a Number, minimum value 12, maximum 100 1389 | - `email` make a validator of email, as given in mongoose documentation. 1390 | - `address` make address a nested data structure which has its own Schema [ **AddressSchema** ??] [ Hint: check mongoose documentation for sub-documents to do it 1391 | 1392 | Create `addressSchema` needed in above example as : 1393 | - `pincode` : Number, required 1394 | - `street` : String, required 1395 | - `phone`: String, length=10 1396 | 1397 | Now try to create this **user** object and **save** it to database. 1398 | - What happens to **addresses** ? How address **document** is stored ? check if it creates a **new collection** in database 1399 | - What happens if you don't provide validated data in any field. [Note: Throw proper errors strings ] 1400 | 1401 | 1402 | ### Related Links/Videos 1403 | 1404 | Queries in Mongoose : [Link](https://mongoosejs.com/docs/queries.html) 1405 | 1406 | 1407 | ## Chapter 8 - React Integration and MERN Stack Live deployment 1408 | 1409 | ### [[ Chapter Notes ]] 1410 | 1411 | 1412 | **Sending data from front-end to Server** 1413 | 1. Fetch : it is in-built API in the browser 1414 | 2. Axios : we will use **axios** as it is easier to use. 1415 | 1416 | **CORS Issues :** 1417 | 1418 | CORS - [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) ([CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS)) is a standard that allows a server to relax the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) 1419 | 1420 | - we will use CORS package to allow cross origin request from **React JS** server to **NodeJS** server as they are on different hosts. 1421 | - `npm install cors` 1422 | - to use cors - 1423 | ```javascript 1424 | const cors = require('cors'); 1425 | 1426 | server.use(cors()) 1427 | ``` 1428 | **HTML Forms** 1429 | 1430 | - `name` attribute on input elements is used to send data keys which are validated with schema in backend. 1431 | 1432 | ### Build a React Project : 1433 | - Run `npm run build` 1434 | - use `build` folder to be hosted on public hosting/static hosting 1435 | 1436 | ### Host a React Project : 1437 | 1438 | you can use `build` folder of react and add it to static hosting of express. 1439 | `server.use(express.static('build'));` 1440 | 1441 | ### Use Routing in Front-end 1442 | 1443 | use wildcard in express route to point to React single page applications (index.html) 1444 | 1445 | ```javascript 1446 | res.sendFile(path.resolve(__dirname,'build','index.html')) 1447 | ``` 1448 | `__dirname` is a variable 1449 | 1450 | 1451 | 1452 | ### Assignments are after Chapter 9 1453 | 1454 | 1455 | ## Chapter 9 - Deploy Live 1456 | 1457 | ### [[ Chapter Notes ]] 1458 | 1459 | **Preparation for deployment** 1460 | - First check whether front-end routes are independent of server, and make all of them relative to `/` 1461 | - Connect MongoDB atlas - in-place of mongo local database 1462 | 1463 | 1464 | ### How to Deploy to Vercel : 1465 | - Commit you code on a github account (personal account for free services) 1466 | - Set Environment Variables on Vercel - like MONGO_URL, PUBLIC_DIR 1467 | - Put a vercel config file - `vercel.json` in your project root directory. 1468 | - After every change, commit your changes - and push code on github. 1469 | - You have to provide permission for github directory to vercel. It will pickup `vercel.json` and `package.json` and deploy your code accordingly. 1470 | - Check video for more details. 1471 | 1472 | 1473 | ### [[ Assignments ]] 1474 | 1475 | - **Assignment 1** : Deploy your own application or API only to a live server like `Vercel` 1476 | - **Assignment 2 [Challenge]** : Deploy your own application or API only to a live server `Railway.app` 1477 | 1478 | 1479 | ### Related Links/Videos 1480 | 1481 | 1. [Heroku Deployment Video](https://www.youtube.com/watch?v=GeXA_MzMR6I) 1482 | 2. [Git Crash Course](https://youtu.be/kviiFelh28g) 1483 | 1484 | 1485 | 1486 | 1487 | ## Chapter 10 - Server Side Rendering 1488 | 1489 | ### [[ Chapter Notes ]] 1490 | 1491 | Server side rendering is done using many templating languages 1492 | - EJS 1493 | - Pug 1494 | - Handlebars 1495 | 1496 | We have used EJS which is one of the most popular one. 1497 | 1498 | Install 1499 | `npm install ejs` 1500 | 1501 | - Control flow with `<% %>` 1502 | - Escaped output with `<%= %>` (escape function configurable) 1503 | 1504 | ```pug 1505 | <% if (product) { %> 1506 |

<%= product.title %>

1507 | <% } %> 1508 | ``` 1509 | 1510 | For passing variable to template engine and render a new page : 1511 | 1512 | ```javascript 1513 | 1514 | const ejs = require('ejs'); 1515 | 1516 | 1517 | ejs.renderFile(path.resolve(__dirname,'../pages/index.ejs'), {products:products}, function(err, str){ 1518 | res.send(str); // this is the rendered HTML 1519 | }); 1520 | ``` 1521 | 1522 | ### How to send HTML FORM data to Express 1523 | 1524 | - You need to have input boxes have proper `name` which will be used as `key` to objects sent to backend. Mostly in form like `name=value` 1525 | - use **action** or for API destination 1526 | `action="/products"` 1527 | - use **method** or for API type 1528 | `method="POST"` 1529 | - use **enctype** with value `application/x-form-urlencoded` 1530 | 1531 | ### [[ Assignments ]] 1532 | 1533 | - **Assignment 1** : Create Server rendered page for `quotes` collection created in 1 of previous assignment. Use a very simple HTML template to display each quote in a list format. You can use other render method of EJS for this task. (**not renderFile**) 1534 | 1535 | 1536 | ### Related Links/Videos 1537 | 1538 | 1. [DOM Series](https://bit.ly/35nMKB7) 1539 | 1540 | ## Chapter 11 - Authentication with JWT 1541 | 1542 | ### Using JWT for generating Auth Tokens 1543 | 1544 | #### JWT library installation 1545 | `npm install jsonwebtoken` 1546 | - Use jwt.io to understand 3 parts of JWT - headers, payload, signature 1547 | 1548 | #### Signing of JWT 1549 | `jwt.sign(payload, secret)` this returns a **token** 1550 | 1551 | #### verifying a JWT token 1552 | `jwt.verify(token, secret)` this returns decoded value of **payload** 1553 | 1554 | We will use HTTP Authorization headers for exchanging these tokens 1555 | e.g. `Authorization = 'Bearer JWT_TOKEN_VALUE'` 1556 | 1557 | **Using RSA algorithm** (public-private key) : check video. 1558 | 1559 | ### Password Hashing 1560 | 1561 | you can use a library like `bcrypt` to hash password, so they are not stored in plain text format 1562 | 1563 | #### Installation : 1564 | 1565 | `npm install bcrypt` 1566 | 1567 | #### Hashing 1568 | 1569 | ```bcrypt.hashSync(userProvidedPassword, saltRounds)``` 1570 | 1571 | #### Verifying Password 1572 | 1573 | `bcrypt.compareSync(loginPassword, AlreadyHashedPassword)` 1574 | 1575 | return `true` of `false` based on verification of password 1576 | 1577 | 1578 | ### [[ Assignments ]] 1579 | 1580 | - **Assignment 1** : Try to make a application which stores JWT in **localstorage**. So that even after you close browser and open site again. Server will still remember you JWT and authenticates you. 1581 | 1582 | 1583 | ### Related Links/Videos 1584 | 1585 | 1. [Localstorage](https://youtu.be/OTkQVPVYW7w) 1586 | 1587 | 1588 | 1589 | #### SESSION MIDDLEWARE [Optional] 1590 | 1591 | [Check Video on Session](https://www.youtube.com/watch?v=v_Ewns3n_Ow) : 1592 | 1593 | Session middleware is used to store session variable for each user on server side. This middleware can make use of any data storage depending on settings. By default it stores session variables in Memory (RAM). 1594 | 1595 | First install express-session middleware 1596 | 1597 | ```shell 1598 | npm install express-session 1599 | ``` 1600 | 1601 | Now you can use it in your express server 1602 | 1603 | ```js 1604 | var server = express() 1605 | const session = require('express-session') 1606 | 1607 | 1608 | server.use(session({ 1609 | secret: 'keyboard cat', 1610 | resave: false, 1611 | saveUninitialized: true, 1612 | cookie: { secure: false } // make secure : true incase you are using HTTPS 1613 | })) 1614 | 1615 | ``` 1616 | 1617 | Now you can use `req.session` object to store any value for a particular user in server session. This value will not interact with similar variable of other users. 1618 | 1619 | ```js 1620 | 1621 | server.get('/user', function(req, res) { 1622 | if (req.session.views) { 1623 | req.session.views++ 1624 | res.json({views:req.session.views}) 1625 | } else { 1626 | req.session.views = 1 1627 | res.send('welcome to the session demo. refresh!') 1628 | } 1629 | }) 1630 | 1631 | ``` 1632 | 1633 | 1634 | #### Assignment for Sessions 1635 | 1636 | In above example we are initializing a variable session for each user. Write similar code in your server 1637 | 1638 | 1. Checkout if its value increases every time you refresh the page. 1639 | 2. What happens when you open URL in another tab. 1640 | 3. What happens when you open URL in another browser 1641 | 1642 | 1643 | #### More Interesting ways of Authentication : 1644 | 1645 | - [Passport JS Authentication](https://www.youtube.com/watch?v=U-S3rgG8hBE) 1646 | 1647 | 1648 | 1649 | ## Chapter 12 - Mongoose Advanced queries, Node Streams, Events etc. 1650 | 1651 | ### [[ Chapter Notes ]] 1652 | 1653 | #### Mongoose Queries 1654 | 1655 | **Sorting**: 1656 | 1657 | find().**sort**({fieldname: 1}) // ascending can be *1, asc, ascending* , Descending values can be *-1, desc, descending* 1658 | 1659 | **Pagination related queries**: 1660 | 1661 | find().**limit**(pageSize).**skip**( pageSize*(pageNumber-1)) // where **pageSize** is number of document results you want to show. 1662 | 1663 | **Population** 1664 | 1665 | Populate() lets you reference documents in other collections. 1666 | 1667 | ```js 1668 | const userSchema = new Schema({ 1669 | firstName: { type: String, required: true }, 1670 | lastName: String, 1671 | cart:[{ type: Schema.Types.ObjectId, ref: 'Product' }], 1672 | email: { 1673 | type: String, 1674 | unique: true, 1675 | validate: { 1676 | validator: function (v) { 1677 | return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(v); 1678 | }, 1679 | message: (props) => `${props.value} is not a valid email!`, 1680 | }, 1681 | required: true, 1682 | }, 1683 | password: { type: String, minLength: 6, required: true }, 1684 | token: String, 1685 | }); 1686 | 1687 | //cart populated example 1688 | const user = await User.findById(id).populate('cart'); 1689 | 1690 | ``` 1691 | **For More details :** 1692 | [Detailed Population Video](https://youtu.be/VuSt5-AwL8Y) 1693 | 1694 | 1695 | 1696 | #### Node Events and Event Emitter 1697 | 1698 | ```javascript 1699 | const em = new EventEmitter() 1700 | 1701 | em.on(eventName, (payloadData)=>{} ) // listeners 1702 | 1703 | em.emit( eventName , payloadData ) // emit events 1704 | ``` 1705 | 1706 | #### Node Streams 1707 | 1708 | A readable stream 1709 | 1710 | ```javascript 1711 | const rr = fs.createReadStream('./data.json'); 1712 | 1713 | rr.on('data', (data) => { // received data event on every file read 1714 | console.log({data}); 1715 | }); 1716 | 1717 | rr.on('end', (data) => { // received end of stream event 1718 | console.log({data}); 1719 | }); 1720 | ``` 1721 | 1722 | ### Socket in Node (Socket.IO) 1723 | 1724 | #### Install Socket IO library 1725 | 1726 | ```npm install socket.io``` 1727 | 1728 | #### Server Side Code 1729 | 1730 | ```javascript 1731 | const server = express(); 1732 | const app = require('http').createServer(server); 1733 | const io = require('socket.io')(app); 1734 | 1735 | io.on('connection', (socket) => { 1736 | console.log('socket',socket.id) 1737 | 1738 | socket.on('msg',(data)=>{ // listener to client-side events 'msg' 1739 | console.log({data}) 1740 | }) 1741 | socket.emit('serverMsg',{server:'hi'} //emitting 'serverMsg' for Client-side 1742 | }); 1743 | 1744 | app.listen(port) 1745 | 1746 | ``` 1747 | 1748 | #### Client Side Code 1749 | 1750 | ```html 1751 | // embeding client-side library which will be downloaded from module installed on Server 1752 | 1753 | 1754 | 1765 | ``` 1766 | 1767 | ### Uploading a file on NodeJS 1768 | - [Uploading a file using Multer middleware Video](https://www.youtube.com/watch?v=qfN6c5FEAQQ) 1769 | 1770 | 1771 | 1772 | ### [[ Assignments ]] 1773 | 1774 | - **Assignment 1** : 1775 | - Make a **simple group chat application** using **Socket.io** library. 1776 | - You need to have a user enter their name in textbox (you can store that in localstorage) 1777 | - After user enters the name : they can see a text box where they can start entering the text messages. 1778 | - Display messages from user and others in a simple html list format. 1779 | - You can align incoming messages from other users to **left** and your own messages to **right** side. 1780 | - Optionally, you can use database to store the old text messages in case you want old chat to be reloaded. 1781 | 1782 | 1783 | ----- 1784 | **------------END OF COURSE---------------------** 1785 | 1786 | ---- 1787 | 1788 | 1789 | 1790 | 1791 | ## MERN STACK PROJECT IDEAS 1792 | 1793 | 1794 | 1795 | ## 1. Resume/Profile Create Web application 1796 | 1797 | An online resume generator application will able to generate resume for students and professional based on their input data. We will have options of downloading the resume or hosting the resume on a particular URL (which user can share). Users will be able to choose between many Template designs for their resume. User data will be stored in database and can be edited later on. 1798 | 1799 | - User Login (Social Logins) 1800 | - Saving user info using validated forms 1801 | - HTML/CSS based templates to design different style of resumes 1802 | - PDF generation of completed resume 1803 | - Providing link on online resume of a person (HTML version / PDF version) 1804 | 1805 | ## 2. Online Tic Tac Toe 1806 | 1807 | Tic Tac Toe is quite ubiquitous popular game. We have a 3 x 3 grid with traditional cross and circle notation. However playing tic tac toe with a distant friend connected via social media is a dream come true. Here is the simple game : 1808 | 1809 | - Connect with Facebook/Google Login for user Identity. 1810 | - Find all people logged in via Facebook on this application 1811 | - Challenge someone to play with you. 1812 | - Have a separate scorecard for each pair of users. 1813 | - show world leaderboard - where you can have your algorithms to show chart toppers - may be number or wins or win/lose ratio. 1814 | - UI should be simple and understandable. 1815 | - Use of animation is preferable but should not be too much 1816 | - Mobile friendliness is required 1817 | - Sounds are optional but can add a lot to the game. 1818 | 1819 | ## 3. E-commerce Application 1820 | 1821 | An Amazon like store to find and buy things. The site will have to interface one for admin and other for general users : 1822 | 1823 | User site features : 1824 | - User must be able to search product via name/ category etc. 1825 | - Each item will belong to atleast one category of items (like electronics) 1826 | - Each item will have some fields - name, price, description, image etc. 1827 | - User can sort items by any field - name , price etc. 1828 | - Cart will have features to add item, remove item, change item quantity, show total etc. 1829 | - User order will be saved in database. 1830 | - User can check details of their old orders. 1831 | 1832 | Admin site features : 1833 | - Admin must login using a secret password. 1834 | - Admin panel should show you list of all available products with their available quanities. 1835 | - Admin can add new items to store or delete old items. You can optionally provide them access to edit item details. 1836 | - Admin can update quantity of any item. 1837 | 1838 | ## 4. Photogram 1839 | 1840 | 1841 | PhotoGram Project is a web app similar to instagram. Purpose of app is to store your photos in an album and add some filters. Users can login and browse their old photos, search them by name, sort using name/date added etc. They can also apply instagram style filters to their photos. 1842 | 1843 | Features : 1844 | 1845 | 1. The user can sign up and create a new account. Check for email duplicate scenario and show an appropriate message if the same email is used for login. 1846 | 2. The user can log in using the previous email/password combination. If email/pass is incorrect to show the appropriate error. 1847 | 3. If the user successfully creates a new account take him to create a new post form - which will have fields photo, caption etc. Date will also be stored in database along with these information. 1848 | 4. After submitting the above form user should automatically be redirected/routed to the photo Gallery page. 1849 | 5. Gallery page should show all cards of logged in user. Only photos uploaded by the same user must be displayed. 1850 | 6. If user login into existing account he must be redirected to Gallery page if he has 1 or more cards uploaded. If no cards are there he must be redirected to the same form as after signup. 1851 | 7. Gallery page should also have a link to form page - using button - “Create new card”. 1852 | 8. The user can also delete cards from gallery page by click on a cross Icon “X” which you can add to all cards in front-end. 1853 | 9. To maintained loggedIn user use sessions and localStorage. 1854 | 1855 | ## 5. Online Pokemon 1856 | 1857 | 1858 | PokeMon requires your help. Save them by picking the right ones. There are some good characters and there are the bad ones. Create a 8×8 Div to make a gameboard. 1859 | 1860 | Game Rules (Offline) 1861 | 1. Pikachu should appear at random places. 1862 | 2. At the same time bad guy (giovanni) will also appear. 1863 | 3. Pikachu and bad guy can’t be on same grid box. 1864 | 4. You have to click Pikachu Grid to save it. 1865 | 5. One correct click means +1 1866 | 6. Consecutive 3 correct means +5 bonus also. 1867 | 7. Wrong answer will mean a strike. 1868 | 8. 3 strikes in continuation means “Game Over” 1869 | 9. A total of 30 points mean Level Complete. 1870 | 10. 1st Level will have Pikachu and Other Guy appearing for 2 second. 1871 | 11. There will be a gap of 3 seconds in between next round. 1872 | 12. With every increasing Level Pikachu and other will appear for lesser time. And gap of round will also be decreased after each Level. 1873 | 1874 | Game Rules (Online) 1875 | 1. All above rules will be applicable accept for their is no 'Game Over' and correct point is given to only the first person who click the pikachu. 1876 | 1877 | 1878 | ## 6. Multi-User Chat Application 1879 | 1880 | Multi-user chat will be a web application where users can chat privately or in group chat. 1881 | 1882 | * Google Login and Custom Login for users 1883 | * User will see a whatapp web like interface on left hand side menu 1884 | * Multi user group chat (For all logged in users) 1885 | * File sharing and File upload 1886 | * Chat Room Should be accessed via name credentials ( later on social login) 1887 | * You can upload a picture in your profile 1888 | * You can change profile settings 1889 | * All online users should be shown in side pane 1890 | * click on a user to selectively chat with him/her 1891 | * Group chat should be visible to all 1892 | * Provide theme color to user which will be used as there chat text also 1893 | * Allow #tag feature where one can tag a statement which be later searched on via a search box 1894 | * Search box should be able to search all text, usernames 1895 | * Time stamp must be visible in Chat (in form of time Ago) 1896 | * Chat should auto scroll to lowest part 1897 | * Use filters to filter out any blacklisted words 1898 | * Block user based on use of blacklisted words 1899 | * See the chat from where you have left 1900 | * only show last 100 messages and load old ones on demand via a scroll function. 1901 | * Use a sound directive for special characters 1902 | 1903 | 1904 | ## 7. Medical Chatbot 1905 | 1906 | Chat bots are the need of the time. With too much information overload and lots of application to interact with - humans need a way to interact with devices in more human way. Chat bots makes your life easy by putting up intelligent question, suggestions and making choice simple enough. We are designing a chat bot which may diagnose simple disease or common problem with health. 1907 | 1908 | - Chatbot should be invoked as soon as you open the website 1909 | - Chatbot should provide few options for any questions you put up 1910 | - By navigation through choices you should be able to reach to final search results. 1911 | - Chat bot should start with category of malice you have and then dive into details of each 1912 | - You can categorize few common symptoms like headache, flus and food allergies. 1913 | - This app will not recommend any medicine but can recommend simple cure which are available in household. 1914 | 1915 | 1916 | ## 8. Quiz / Online exam Application 1917 | 1918 | 1919 | Admin Panel 1920 | 1921 | - Add a question 1922 | - Edit a question 1923 | - Remove question 1924 | - Change the order of questions(Move the questions up or down) 1925 | - Choose the type of answer for the question(short answer, long answer, MCQ etc.) 1926 | - Time limit for a question 1927 | - Time limit for the test 1928 | - Negative marking 1929 | - Choose randomization of questions for adjacent systems 1930 | - Choose different question for different students(Set - A,B,C,D) 1931 | - Save the state of answers and auto submit at the end of test if the student has not submitted the test himself 1932 | - Making test go live after editted in private mode. 1933 | 1934 | Examinee side 1935 | 1936 | - Login 1937 | - One question per page. 1938 | - Mark a question as “remind me” later 1939 | - Show overall progress which show attempted / unattempted questions. 1940 | - Timer showing the timing remains or time completed 1941 | - Submit paper at end of time automatically. 1942 | - Manual submit option. 1943 | 1944 | 1945 | ## 9. Party/Trip Expense planner 1946 | 1947 | 1948 | This app can be used to manage expenses between friends who are planning an event/trip/party. This app will help in adding all expenses done by any individual. It will provide the report of who owes how much and money should be given to whom. 1949 | 1950 | Features : 1951 | 1952 | - Social login 1953 | - Creating a group of friends who have account on this app. 1954 | - Make a new event/trip (name of event) 1955 | - Adding entries of money given by individuals. (Who paid, for what, how much) 1956 | - Updating any old entry (but with having updated date shown and count of updated version) 1957 | - Deleting entry by confirmation of multiple users. 1958 | - Functionality to end the event - so no new entries can be made. 1959 | - Functionality to show who owes and who should get the money. 1960 | - Automating mails and messages to every member about how much they owe or will get at end of trip. 1961 | 1962 | 1963 | ## 10. Map Based Spot Add/Search 1964 | 1965 | * Create a spatial database for adding and searching your favorite place on map. 1966 | * You can take a city map via google map Api. 1967 | * Coordinates should be marked with extra information stored on your own database. 1968 | * One should be able to add points on map via clicking on map and filling a simple form. 1969 | * Form must contain name of place, description and category of place like (Cafe, restaurant etc.) 1970 | * Also you can represent you places with some icons on map. 1971 | * In Search Section, one must be able to search places according to category, distance from you, 1972 | name of the place etc. 1973 | * Results must be arranged according to relevance and then according to distance from you. For 1974 | e.g a direct name matching should be of higher priority to that of distance of that place. But in 1975 | case someone is searching by category names one should prefer to go by distance. 1976 | * In Search, If somebody click on a place they must get a small info box about the place. 1977 | * In Search, if somebody clicks on a place there must be a provision to get direction which must 1978 | redirect to google maps application for exact direction. Note : you don’t need to integrate google 1979 | maps in your application for this. Just redirect them in another tab or app. 1980 | * Only admin can edit place in the account, admin account should be kept secret. 1981 | * Search must be available to all people. However they can give feedback about the place but that 1982 | will only be visible after approved by admin. 1983 | 1984 | 1985 | ## 11. Calendar Reminders App: 1986 | 1987 | - Create a todo list application with a Nice UI 1988 | - You can add/remove tasks etc. 1989 | - which should have task with given date and time 1990 | - Use system date and time pickers 1991 | - Each task will have some starting time which should integrate with your system calendar.(Google calendar) 1992 | - Whenever task is pending system will reminds you through calendar app or email or SMS (you can choose notification preferences) 1993 | 1994 | 1995 | ## 12. Pomodoro App (Time Management) 1996 | 1997 | - Create a todo list styled task your perform daily like Reading, Jogging, cooking etc. 1998 | - Track every task in terms of pomodoro breaks ( 1break 25 min) 1999 | - After 4 short break take a long break 2000 | - Pomodoro Timer should be circular and it should raise and alarm after time is over. 2001 | - You can take a break and start pomodoro timer again on same task or differs task 2002 | - Your list will show how many pomodoro times you have given to each task 2003 | 2004 | Refer to this URL 2005 | 2006 | https://zapier.com/blog/best-pomodoro-apps/ 2007 | 2008 | ## 13. Popular content search engine and pinboard 2009 | 2010 | - Use #hashtags to search content through many social apps like facebook, instagram, twitter, reddit etc. 2011 | - Sort by popularity 2012 | - Show different media into one list - images, videos, status etc. 2013 | - Bookmark content for making collections and pins 2014 | - You can save items in diff boards - sports, tech, weather, politics 2015 | 2016 | ## 14. Buy/Sell App 2017 | 2018 | - Login 2019 | - Sign up - Ask for interested in buying or selling or both 2020 | - Messages/offers for buy 2021 | - Push notifications for any buy/ sell offer 2022 | - category of item 2023 | - negotiable / non negotiable 2024 | - send an offer 2025 | - mark as favorite 2026 | 2027 | 2028 | ## 15. Table Booking system 2029 | 2030 | When you visit a restaurant you have to book a table for people. If you book in advance, restaurant has to plan according to available options. 2031 | 2032 | - Choose restaurnt 2033 | - Auto detect location and resturant nearby sorted by distance 2034 | - filter - number of persons, pure veg, cuisines, ratings etc. 2035 | - Book seats 2036 | - On restaurant side they will have a limited number of seats. 2037 | - Show how many seats are available now. 2038 | - If seats are over disable booking at restaurant 2039 | - Admin panel : Can login into restaurant and change number of seats available 2040 | 2041 | 2042 | ## 16. Book Search Engine 2043 | 2044 | - Login to account, 2045 | - ratings, 2046 | - add/ edit / delete a review, 2047 | - the social reading graph 2048 | - recommendations of books 2049 | - Author’s information 2050 | - user’s information - 2051 | - search book by title / ISBN / author 2052 | - read reviews of a book by providing its title / ISBN / author 2053 | - read/write comment for a book 2054 | - Follow / unfollow an author 2055 | - Follow/ unfollow other users 2056 | - Find a group 2057 | - Join a particular group 2058 | - Create a new group 2059 | - Like / unlike a resource 2060 | - Add/ edit / delete a book shelf 2061 | - add /delete books to book shelf 2062 | - User’s read status- set status and get any user’s status 2063 | 2064 | 2065 | 2066 | ## 17. URL shortner App 2067 | 2068 | - generator a short url 2069 | - redirect to the main webpage 2070 | - track how many people visited that url 2071 | - how many clicked on the short url and navigated to the designated page 2072 | - which device they used - mobile / desktop 2073 | - optional - require a user to log in to view private url 2074 | 2075 | 2076 | ## 18. Movie Recommendation based on IMDB rating 2077 | 2078 | - search for movies by title 2079 | - get all the episodes of any TV series. 2080 | - get year of release of a movie 2081 | - get rating of movie 2082 | - get movie by genre 2083 | - get movie by release year 2084 | - get movie by actors 2085 | 2086 | 2087 | ## 19. Railway App (PNR checking & Live running status) 2088 | 2089 | - login 2090 | - add my journey details (PNR) 2091 | - get current PNR status 2092 | - push notifications on day of journey 2093 | - set timing for reminder - a day before, an hour before etc. 2094 | - get train running live status by API 2095 | 2096 | ## 20. Blog Application 2097 | 2098 | - Login 2099 | - Create a new blog - image, title, text content (rich text containing HTML based content) 2100 | - Use can see list of their own blogs and can delete any old blog. 2101 | - Show list of blogs in home page with card format. 2102 | - You can see your blogs and everyone else blog on home page 2103 | - Sort blogs by author, date created etc. 2104 | - Create category of blogs and classify blogs under a catgeory. 2105 | - Create option to share blog via social media. 2106 | - Create like feature for blog. A use can one like once for same blog. 2107 | 2108 | 2109 | ## 21. Notes Application 2110 | 2111 | - User can login 2112 | - Make a note making application similar to Google Keep. 2113 | - User can make a board in which they can add some notes. Boards are like study, watch, books etc. 2114 | - User can make text notes, add images and files attachements also. 2115 | - User can change card color according to priority of tasks (Red, yellow, green) 2116 | - User can update and delete cards. 2117 | - User can search cards with text search. 2118 | 2119 | ## 22. Currency Converter App 2120 | 2121 | - Show a list of top currencies and countries sorted by their value for today. 2122 | - List of countries will be displayed with their flag icons. [Example UI Link](https://play.google.com/store/apps/details?id=com.easy.currency.extra.androary&hl=en) 2123 | - There should be two input "Current Currency" and "Exchange Currency". e.g Current Currecy as "INR" and Exchange Currency as "USD". 2124 | - Automatic conversion should be done on change of any change in Dropdown menus. 2125 | - You can reverse the currency options by simple click. 2126 | - Application should store old conversion records and create a simple list of it. 2127 | 2128 | 2129 | ## 23. Appointment booking app 2130 | 2131 | Appointment book app creates and event in which you can book slots. It can help a professional like doctor, interviewer to provide slots to other person in which they can visit. Calendly site is a good example of such an app 2132 | 2133 | - User can login 2134 | - Creates an event with name / description/ Date. Start and endtime. 2135 | - User chooses how long will be slots between start and end time. (10 mins). 2136 | - Final user saves the event setting and gets a URL. 2137 | - User shares the URL with all non logged in users. 2138 | - These user can only see Name of the event, date, start time/endtime and available slots. 2139 | - User books a slot by passing his email, name information. 2140 | - If a slot is booked that will be removed from available slot list and other users will not be able to book the same slot. 2141 | - If all slots are booked, users will be shown a message that no slot is available. 2142 | 2143 | ## 24. News application. 2144 | 2145 | This news application will be something similar to google news and will pull news from major news channels and apis. 2146 | 2147 | - News will be categoriesed according to tags India, sports, world, movies etc. 2148 | - News can be bookmarked by user for later reading. 2149 | - User can search new according to their keywords. 2150 | - Database will store old news items and they will also be searchable. 2151 | - News will be sorted according to new to old. 2152 | 2153 | ## 25. Meme Genrator App 2154 | 2155 | Make an advanced interface for creating memes! Allow the user to upload an image, write a caption, and build a meme with the Imgflip api. To take it to the next level, allow the user to share their meme on Twitter, Facebook, and other social platforms. 2156 | 2157 | - User should upload a image of some restricted dimension (max width fixed) 2158 | - User can provide some caption to the image. 2159 | - Captions can be changed in font-size, font-color and orientation. 2160 | - Also one can move captions up or down in the image. 2161 | - Finally user can generate the meme and get a final URL. 2162 | - User can share the URL to other friends to show the meme. 2163 | - As an extra feature one can provide download image feature to user. 2164 | 2165 | 2166 | ## 26. Tetris Game 2167 | 2168 | Example : [Check this](https://github.com/skidding/flatris) 2169 | 2170 | 2171 | ## 27. Break Journey App 2172 | 2173 | It is easy to make travel booking for direct journey from one city to another. But in case you don't find direct flights, trains etc. You might have to break the journey and find trains from a intermediate station and change from their to get to end destination. 2174 | 2175 | - User will provide start and end destination 2176 | - User will provide a intermediate city from where they can change. 2177 | - Interface will provide the connecting journey options on same date. 2178 | - Care must be taken in timings of arrival and departure - so that one can continue the journey. 2179 | 2180 | [Back To Top](#full-stack-course-2023) 2181 | 2182 | # Redux JS MasterClass 2183 | 2184 | 2185 | Hi, This is course page of **CoderDost Youtube Channel** Redux JS 2023 Course [Video Link ](TODO), 2186 | 2187 | 2188 | 2189 | ### How to use this code : 2190 | 2191 | 2192 | 2193 | #### You can **download code** in 2 ways : 2194 | 2195 | 2196 | 2197 | 1. **Git Commands** 2198 | 2199 | 2200 | 2201 | - use `git clone ` 2202 | 2203 | 2204 | 2205 | - checkout 'redux' branch - All Chapters are in same branch but different folders `git checkout redux` 2206 | 2207 | 2208 | 2209 | - run `npm install` inside the each folder before running the code 2210 | 2211 | 2212 | 2213 | 2214 | 2215 | 2. If you are not comfortable with git, directly **download the branch as Zip**. 2216 | 2217 | 2218 | 2219 | - Choose branch related to the Redux e.g. `react`. It contains all chapter 2220 | 2221 | 2222 | 2223 | - run `npm install` inside each chapter folder before running the code 2224 | 2225 | 2226 | 2227 | 2228 | 2229 | # Redux JS Series 2230 | 2231 | 2232 | 2233 | 2234 | ## Chapter 1 - Redux Concepts and Pattern 2235 | 2236 | 2237 | 2238 | - **Assignment 1** : Using the concepts learnt in this chapter. Make a Async type of call from a new reducer to any online API like [JSON Placeholder Posts](https://jsonplaceholder.typicode.com/posts). Also show proper loading messages in console. Like - `loading posts...`, `posts loaded` , `posts fetching failed`. Also add those posts to a state of reducer in a sorted manner (sort by `title`) 2239 | 2240 | - **Assignment 2** : Check out IMMER library and run some example and see how you can make mutating updates like `state.amount++` inside reducer logic. And still it work perfectly in redux. 2241 | [Immer Link](https://immerjs.github.io/immer/) 2242 | 2243 | ### Related Videos 2244 | 1. De-structuring Assignment : [Long Video](https://youtu.be/sNhqFofQhFs) | [Object De-structure Short Video](https://youtube.com/shorts/H3MKXE69_c8) | [Array De-structure Short Video](https://youtube.com/shorts/ONGyMq49kZY) 2245 | 2. Import/Export : [Long Video](https://youtu.be/7P5JUMc1cI4) | [Short Video](https://youtube.com/shorts/sUUOSWlwfM8) 2246 | 3. Spread Operator : [Long Video](https://youtu.be/X4Iv0TBHDQ4) | [Short Video](https://youtube.com/shorts/5dBZGyXutx8) 2247 | 4. [Callbacks](https://youtu.be/rx-y7U4x4wc) 2248 | 5. [Promises](https://youtu.be/aA4-VNZK2s0) 2249 | 6. [Async Await](https://youtu.be/rdy8ZV0LXV0) 2250 | 2251 | 2252 | 2253 | ## Chapter 2 - Redux With React Application 2254 | 2255 | - **Assignment 1** : Add more cases in Account Reducer called `decrementByAmount` . Also check that amount should not be decremented in case `amount` to be decremented is less than account Balance. For e.g. if total amount in account is 10, you can't decrement by 11. Also show an error in that situation to user. 2256 | 2257 | - **Assignment 2** : Check out IMMER library and run some example and see how you can make mutating updates like `state.amount++` inside reducer logic. And still it work perfectly in redux. 2258 | [Immer Link](https://immerjs.github.io/immer/) 2259 | 2260 | ### Related Videos 2261 | 1. [React-Redux in Class Components](https://youtu.be/FIjtWnypwMo) 2262 | 2263 | 2264 | ## Chapter 3 - Redux Toolkit with React 2265 | 2266 | - **Assignment 1** : Add more cases in Account Reducer called `decrementByAmount` . Also check that amount should not be decremented in case `amount` to be decremented is less than account Balance. For e.g. if total amount in account is 10, you can't decrement by 11. Also show an error in that situation to user. 2267 | 2268 | - **Assignment 2** : Create more async thunk examples, we only tried GET USER- `READ` example. But try the `CRUD` example to `Create` new user, `Update` the user, `Delete` the user. 2269 | - You have to create a list of `users` which has names of all users in local database 2270 | - You an `INPUT BOX` to add new users to `list` , users show also add to database and updated in list.[Hint: use REST API concepts for Create API, POST method] 2271 | - You can put a `delete` button on end of list item. On clicking of this button `user` list item will be deleted from database. [Hint: use REST API concepts Delete API, DELETE method] 2272 | - You can put a `selected` button on end of list item. On clicking of this button `user` list item will change colors. [Hint: use REST API concepts Update API, PUT/PATCH method] 2273 | - 2274 | ### Related Videos 2275 | 1. [ REST API concepts](https://youtu.be/xrB51fPM1K4) 2276 | 2. [REST API complete explanation in NodeJS](https://youtu.be/ChVE-JbtYbM?t=10913) 2277 | 2278 | 2279 | ## Chapter 4 - Redux Toolkit Query 2280 | 2281 | 2282 | 2283 | ## Chapter 5 - Redux Toolkit with Async Thunk - Product and Cart Project 2284 | 2285 | - **Assignment 1** : Add a `` on Cart Items to `+` and `-` buttons which should increment or decrement quantity of item in the cart. Also check if Cart total is coming correct. 2287 | 2288 | 2289 | ## Chapter 6 - Redux Saga Introduction [Optional chapter] 2290 | 2291 | - **Assignment 1** : Complete the `delete` and `update` feature using Redux Saga middleware 2292 | 2293 | 2294 | 2295 | [Back To Top](#full-stack-course-2023) 2296 | -------------------------------------------------------------------------------- /json-placeholder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/coderdost/full-stack-dev-2023/16d8e22bc5ff9145df34b17a325847ab8a522178/json-placeholder.png --------------------------------------------------------------------------------