-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotesWithRoadMap.txt
More file actions
1591 lines (1242 loc) · 76 KB
/
NotesWithRoadMap.txt
File metadata and controls
1591 lines (1242 loc) · 76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
FULL STACK COURSE 2023
REACT MasterClass Course Material - HERE
React MasterClass 2023 Video
Assignment Solutions Video
MongoDB ip address 0.0.0.0/0 by default.
NODE MasterClass Course Material - HERE
NODE 2023 Video
Redux MasterClass Course Material - HERE
REDUX 2023 Video
React JS MasterClass
Hi, This is course page of CoderDost Youtube Channel React JS 2023 Course Video Link ,
How to use this code :
You can download code in 2 ways :
Git Commands
use git clone <repository_url>
checkout branch according to Chapter number git checkout react-1
run npm install inside the root directory before running the code
If you are not comfortable with git, directly download the branch as Zip.
Choose branch related to the Chapter e.g. react-1
run npm install inside the root directory before running the code
React JS Series
Chapter 1 - Introduction to React & Setup
Assignment 1 : If we delete node_modules. How to run our app again successfully ?
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.
Special Assignments ==============
Assignment 3 : Create a Page with multiple React Apps. Both React Apps should be independent of each other.
Assignment 4 : Try to build a react app using other toolchains like Vite
Related Videos :
De-structuring Assignment : Long Video | Object De-structure Short Video | Array De-structure Short Video
Import/Export : Long Video | Short Video
Chapter 2 - Components - JSX and Props
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.
resume = {
experience : [ { year:2012, company:'xyz', role:'something' }],
education:[ ],
skills : [ 'react js', 'node js']
.....
...
}
You can choose any simple HTML layout and convert it to React Components
Example Link : Resume HTML
Special Assignments ==============
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
< Border>
< Component >
< Border />
Related Videos :
De-structuring Assignment : Long Video | Object De-structure Short Video | Array De-structure Short Video
Import/Export : Long Video | Short Video
Spread Operator : Long Video | Short Video
Chapter 3 - Conditional Rendering & Lists
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.
< List layout="numbered" items={items}/>
< List layout="alpha" items={items}/>
< List layout="bullet" items={items}/>
Assignment 2 : This is continuation of previous assignment RESUME Builder
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.
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.
Conditionally put some styling to Resume. Like light theme or dark theme or any other way you can switch the CSS layouts.
resume = {
experience : [ { year:2012, company:'xyz', role:'something' }],
education:[ ],
skills : [ 'react js', 'node js']
.....
...
}
You can choose any simple HTML layout and convert it to React Components
Example Link : Resume HTML
Related Videos :
Ternary Operator : Video
Logical AND (&&) : Video
Higher Order functions (map, filter, reduce) : Video
Import/Export : Long Video | Short Video
Chapter 4 - Events && Event Bubbling
Assignment 1 : Make a simple page with 1 Image, 1button, 1 form Input text box and try to apply these events .
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.
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 ?
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".
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.
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.
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 ]
Assignment 4 : This is continuation of previous assignment RESUME Builder.
Add a print button to print the current resume. You can use a DOM method window.print to print the PDF.
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 ]
Special Assignments ==============
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.
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.
Related Videos :
HTML DOM Elements and manipulation Video
HTML DOM Events and manipulation : Video
Chapter 5 - State, useState Hooks
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 ?
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.
Chapter 6 - Form , Synthetic Event Object & Lifting State up
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. On selection of the any option from dropdown, its value should be displayed on console.log
const nations = [
{ name: 'India', value: 'IN' },
{ name: 'Pak', value: 'PK' },
{ name: 'Bangladesh', value: 'BG' },
]
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 - If you type only "in" it should show things like "India" / "China" as both have in in it.
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.
Assignment 3 :
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.
first component will be your RESUME document which is only for reading purpose.
second component will be this FORM
you have to manage the state in between
only Add functionality is required in this assignment
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.
Assignment 4 : Try this challenge : https://beta.reactjs.org/learn/state-a-components-memory#challenges
Related Videos :
HTML Forms-1 Video
HTML Forms-2 : Video
MINI PROJECT
Project 1 - TODO App
Todo app can be used to maintain a list of your pending daily items. A Simple todo list must have these features
You can add any new item to TODO list
You can click on any item to mark it as done, if you have done that by mistake - you can click again to undo.
You can delete any item (completed or pending)
You get a total of completed items and overall items on the list.
You can move list items "Up" or "Down" using buttons.
Output
Additional Features
KEYBOARD BASED Features :
use ENTER key on keyboard to add a new item.
when you click on an item, it should be selected (you can change style to show it is selected)
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.
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.
Other Features :
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.
Show the date & time at which list item was added.
Order by : Todo Item names, Date added, Completed.
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.
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.
Delete item via swipe gesture - like swipe to right on mobile phone. [Hint: You have to find an event type for this ]
Advanced Features :
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. LocalStorage Video LocalForage Video
ANIMATION BASED Features [optional] :
Enter Animation : Animate list item on adding.
Exit Animation : Animate list item at removal.
Chapter 7 - More State & useEffect hooks
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 ]
Assignment 2 : This is continuation of previous assignment RESUME Builder.
Add functionality to delete the items from resume.
Add functionality to update the items from resume.
you have to manage the state in between
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.
Check the output can be printed perfectly in PDF.
Chapter 8 - useReducer
Assignment 1 : Try this challenge : https://beta.reactjs.org/learn/extracting-state-logic-into-a-reducer#challenges
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.
Related Videos :
REDUX - Understand it in Simple way Video
Chapter 9 - Context API & useContext
Assignment 1 : Try this challenge : https://beta.reactjs.org/learn/passing-data-deeply-with-context#challenges
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.
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.
Chapter 10 - Context API with useReducer [Redux architecture]
Special Assignments
Assignment 1 : Make a useCounter Hook: To keep track of a number that can be incremented or decremented.
const [count, increment, decrement] = useCounter(0);
Chapter 11 - useRef
Assignment 1 : Try this challenge:
https://beta.reactjs.org/learn/referencing-values-with-refs#challenges
Assignment 2 : Try this challenge:
https://beta.reactjs.org/learn/manipulating-the-dom-with-refs#challenges
Assignment 3 : Make a useWindowSize Hook: which returns size of current browser window.
const [width, height] = useWindowSize();
Related Videos :
Complete DOM Course playlist Video
Chapter 12 - useEffect and API calling
Assignment 1 : Try this challenge :
https://beta.reactjs.org/learn/synchronizing-with-effects#challenges
Assignment 2 : Try this challenge :
https://beta.reactjs.org/learn/removing-effect-dependencies#challenges
Assignment 3 : Try this challenge :
https://beta.reactjs.org/learn/reusing-logic-with-custom-hooks#challenges
Assignment 4 Use JSON Placeholder API (link given below).
You have to create a button which can get some posts and show them in a List.
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]
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.
Try to optimize by :
Only getting comments of required Post items (not all at a time)
Storing somehow the old comments of closed list items. So you will not fetch them again, when your show comments again.
enter image description here
Related Links :
Mockaroo fake data APIs Link
JSON placeholder API Link
Chapter 13 - Memoization - useMemo, useCallback, memo
Assignment 1 : Implement a component that displays a list of items. The component should memoize the list of items to prevent unnecessary re-rendering.
Assignment 2: How to use memoization in the JSON Placeholder API assignment in previous problem. Can you try to optimize it using useMemo/useCallback ?
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 ]
Chapter 14 - Advanced React - Part 1
Assignment 1 : 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
Chapter 15 - Advanced React - Part 2
Assignment 1 : 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 ?
--- END OF REACT COURSE ------
Node JS MasterClass
Hi, This is course page of CoderDost Youtube Channel NODE JS 2023 Course Video Link
How to use this code :
You can download code in 2 ways :
Git Commands
use git clone <repository_url>
checkout branch according to Chapter number git checkout node-1
run npm install inside the root directory before running the code
If you are not comfortable with git, directly download the branch as Zip.
Choose branch related to the Chapter e.g. node-1
run npm install inside the root directory before running the code
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)
Chapter 1 - Introduction to Node, NPM, Package.JSON
[[ Chapter Notes ]]
Node JS installation from official site nodejs.org - use only LTS versions
Use terminal / command prompt to check installation : node -v npm -v
VS Code installation directly from code.visualstudio.com site
Use VS code terminal to run commands
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
Running any JavaScript file from node using node filename.js
Modules are basic containers in Node/JavaScript system. 1 file can be one module in Javascript.
Two type of Module Systems in node JS are - CommonJS module and ES Modules.
- CommonJS Module
//lib.js
exports.sum = function(){}
//index.js
const module = require('./lib.js')
module.sum();
- ES Module
//lib.js
export {sum}
//index.js
import {sum} from './lib.js'
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.
Reading files can be Synchronous or Asynchronous. Async is most preferred method in NodeJS. As there is NO blocking of I/O in NodeJS
Node project can be initialized with npm init command which also creates package.json file
package.json is a configuration file for node projects which has scripts, dependencies, devDependencies etc
npm install <package-name> is used to install any online modules available for node on NPM repository online.
nodemon is a package for running node server and track live changes to re-start again.
scripts inside package.json can be used like npm run <script-name> e.g npm run dev. Only for npm start you can avoid run.
use npm install -g <package.json> to install packages globally on your system. Not just in the project but useful all over your system.
Node versions are formatted like 4.1.9 where these are major.minor.patch versions.
you can install all dependencies again using npm install again
package-lock.json has exact versions installed and link of dependencies of each package.
use npm update to update packages safely. npm outdated shows outdated and latets versions of packages installed in your package.json
use npm uninstall <package-name> to uninstall packages from package.json
node_modules should not be shared - you can make .gitignoreto ignore them to be uploaded.
[[ Assignments ]]
Assignment 1 : If we delete node_modules. How to run our application again successfully ?
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 ]
Assignment 3 : Explore the os module in Node Js from their documentation. What all info you can access from it about your operating system ?
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.
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 ?
Related Links/Videos
Callbacks
Promises
Async Await
Import/ Export example
Event Loop in Node JS
Chapter 2 - Server Concepts with Node - http module
[[ Chapter Notes ]]
HTTP requests
Request object comprises of many properties, but important ones are :
Type of Request : GET, POST, PUT, DELETE etc.
Headers : Meta data sent by your browser like browser name, cookies, authentication information etc.
Query Parameters (url?name=john) : This is used in GET requests to send data to server
Route Params (url/john)
Body data : This is used in POST and other requests to send data to server
HTTP responses
Response object comprises of many properties, but important ones are :
Headers : Meta data sent by your server back to client like server name, content size, last updated time etc.
Response status code (200, 404, 403, 502)
Response body : Actual data to be sent to client : HTML, JS, JSON, CSS, Image etc.
More info
HTTP requests and responses can be tracked from Dev Tools > Network Tab
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.
Server can simply be said as a function which receives a request and returns a response. [ This is just for understanding]
There are many Headers which exists on request and responses - shared a link below with list of existing headers.
We can use Server to do 3 things:
Static file Hosting : Sending normal files without formatting or modifying.
Server Side Rendering : Mixing data with templates and rendering dynamic views (dynamic web pages)
Web APIs : Sending data via some APIs/ endpoints.
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"
POSTMAN is a software for doing complex API requests.
[[ Assignments ]]
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 ?
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
So output of a request with GET /demo will be different from POST /demo [ Use POSTMAN for requests]
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 ?
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 ]
Related Links/Videos
Web Server Concepts in 1 Video
List of HTTP headers
List of HTTP methods
dummy JSON site
Chapter 3 - Express JS
[[ Chapter Notes ]]
ExpressJS is de-facto Node framework - and used in most Node applications which are used as web server.
You can install express npm install express
Express has few level of methods :
Application methods : e.g. app.use()
Request methods
Response methods
Middleware methods
Router methods
Response methods (res is our response objects)
res.send() - for sending HTML
res.sendFile() - for sending File
res.json - for sending JSON
res.sendStatus(404) - for sending HTTP status only
HTTP Request Types we generally use :
GET
POST
PUT
DELETE
PATCH
API / Endpoints / Routes are used inter-changeably but they are related to server paths.
Middle-ware : Modifies the request before it reaches the next middleware or endpoints.
Sequence of middleware is very important, as first middleware is first traversed by request.
Middle-wares can be used for many use cases, like loggers, authentication, parsing data etc.
Middle-ware can be :
Application level : server.use(middleware)
Router level : server.get('/', middleware, (req,res)=>{})
Built-in middleware : express.json() [ for parsing body data], express.static()[for static hosting]
External Middle-wares - like morgan
Request properties (req is our request object)
req.ip - IP address of client
req.method - HTTP method of request
req.hostname - like google.com / localhost
req.query - for capturing query parameters from URL e.g. localhost:8080 ? query=value
req.body -for capturing request body data (but its needs a middleware for body data decoding)
req.params - for capturing URL parameters for route path like /products/:id
Static Hosting : we can make 1 or more folders as static hosted using express.static middleware. server.use(express.static(< directory >)) Static hosting is like sharing a folder/directory and making its file readable as it is. Note : index.html is default file which would be read in a static hosted folder, if you don't mention any file name.
3 major ways of sending data from client to server via request are :
1. Send data via URL in Query String
This is easiest method to send data and mostly used in GET request.
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 &.
To read such data in express you can use req.query :
server.get("/demo",function(req,res){
console.log(req.query) // prints all data in request object
res.send(req.query); // send back same data in response object
})
Assignment 1 :
Make above server with API endpoint /demo as shown above :
Try to call this API in your browser http://localhost:8080/demo?name=Youstart - this will return a response of req.query JSON object
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.
2. Send data via Request Params
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
server.get("/demo/:name/:subject",function(req,res){ console.log(req.params) // prints all data in request object res.send(req.query); // send back same data in response object })
So sequence of values matter in this case. As values sent from client are matched with name and subject params of URL later.
Assignment 2 :
Make above server with API endpoint /demo as shown above :
Try to call this API in your browser http://localhost:8080/demo/Youstart/Express - this will return a response of req.params JSON object
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.
3. Send data via Request Body
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
Use a HTML Form and make method value as POST. This will make all name=value pair to go via body of request.
Use special browsers like POSTMAN to change the body directly. (We will see this example in next classes)
server.post("/demo",function(req,res){
console.log(req.body) // prints all data in request object
res.send(req.body); // send back same data in response object
})
Related Links/Videos
Middleware Explanation video
List of useful 3rd party middleware for Express
List of HTTP response status
Chapter 4 - REST API using Express JS
[[ Reading Material ]]
HTTP Methods
The HTTP method is the type of request you send to the server. You can choose from these five types below:
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.
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.
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.
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.
REST API are a combination of METHODS( GET, POST etc) , PATH (based on resource name)
Suppose you have a resource named task, Here is the example of 5 REST APIs commonly available for task.
READ APIs :
GET \tasks : to read all
GET \task\:id : to read a particular task which can be identified by unique id
CREATE APIs :
POST \tasks : to create a new task object (data will go inside request body)
UPDATE APIs :
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.
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
DELETE APIs :
DELETE \task\:id : to delete a particular task which can be identified by unique id.
[[ Chapter Notes ]]
REST API is a standard for making APIs.
We have to consider a resource which we want to access - like Product
We access Product using combination of HTTP method and URL style
REST API ( CRUD - Create , Read , Update, Delete) :
CREATE
POST /products - create a new resource (product)
READ
GET /products - read many resources (products)
GET /products/:id - read one specific resource (product)
UPDATE
PUT /products/:id - update by replacing all content of specific resource (product).
PATCH /products/:id - update by only setting content from body of request and not replacing other parts of specific resource (product).
DELETE
DELETE /products/:id - delete a specific resource (product).
[[ Assignments ]]
Assignment 1 : Make an API similar to explained above for Quotes take dummy data from same site (dummy json quotes)
Related Links/Videos
Middleware Explanation video
Chapter 5 - Backend Directory Structure / MVC / Router
[[ Chapter Notes ]]
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.
In Our Project this will be : Model - Database Schema's and Business logics and rules View - Server Side Templates (or React front-end) Controller - functions attached to routes for modifying request and sending responses. It's a link between the Model and View.
Router
These are like mini-application on which you can make set of Routes independently.
Routers can be attached to main Server App using server.use(router)
Arrange Directory in Server like this :
Controllers - file containing functions which are attached to each route path Routes - files containing routers Models : to be discussed in later chapters Views: to be discussed in later chapters
[[ Assignments ]]
Assignment 1 : Read More about Model View Controller online, link given below.
Related Links/Videos
Model View Controller
Chapter 6 - MongoDB - Server / Mongo Shell (CLI) / Mongo Atlas
[[ Reading Material]]
MongoDB is NoSQL database which has a JSON like (BSON data) data storage.
Setting up Database Server and Connecting with Mongo Shell
After installing MongoDB community server package on your system - you will have to start the database server using command :
mongod
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
Once server is started - you can use mongo client to connect to local server
mongo
Now you can use several commands to work with database:
show dbs
This will list all the database in your system
use <dbname>
This will command will let you switch to a particular
Understanding MongoDB structure
Hostname
Database
Collection
Document
Hostname is Database server address - like localhost or db.xy.com. In mongoDB hostname generally uses mongodb protocol to connect. So URLs are generally are of shape : mongodb://localhost:27017
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
There can be many collections inside a database - collection is a group of documents of similar kind - students, teachers, courses etc
Finally document is basic entity of storage in Mongod, it looks very similar to an object in JSON. (However it is BSON)
MONGO CLI
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
Read the commands here
Assignment 1
Try these commands given in Mongo CLI reference docs.
Show database
Use database
Show collection
Create Query (insertOne, insertMany)
Read Query (find, findOne)
Update Query (updateOne)
Delete Query (deleteOne, deleteMany)
Delete database (drop)
Assignment 2
Mongodump and Mongorestore
These utilities comes with community server and can be found in CMD/terminal. They are not the part of Mongo CLI client.
Mongodump command is used to take backup of complete database or some collections
mongodump --db accounts
Above command takes backup of database accounts and stores into a directory named dump
Mongorestore command is used to restore database
mongorestore --db accounts dump/accounts
Above command restore your database accounts from backup directory dump
Task : Use these commands on terminal/CMD (not inside mongo client)
Take a backup of database you created in assignment 1.
Restore the backup of database from dump directory.
Using MONGODB NODE.JS DRIVER [ OPTIONAL READING - as we will not use Mongo Driver ]
To install MONGODB NODE.JS DRIVER use this command
npm install mongodb
You can setup database in Node server using following commands :
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
});
Now this db handle can be used to perform any CRUD operation using MongoDB NodeJS driver.
CRUD Functions links
Create - Shell Version / Node Version
Read - Shell Version / Node Version
Update - Shell Version / Node Version
Delete - Shell Version / Node Version
[[ Chapter Notes ]]
Mongo Server
You can install MongoDB community server for your system and set the Path to bin folder
You can choose your own database path while starting the mongod server
mongod --dbpath <path-to-db-directory>
Mongo Compass : UI Client to see mongo server (local or remote)
Mongo Shell : Command-line based mongo client for checking mongo database.
Some Mongo Commands:
Top Level commands :
(run from anywhere inside the shell)
show dbs;
use < database-name > - to choose a database and go inside its prompt
Database CRUD commands :
(run only from inside a database)
CREATE COMMANDS
db.< collectionName >.insertOne( newDocument )
db.< collectionName >.insertMany( documentArray )
READ COMMANDS
db.< collectionName >.find( filterObject ) - to read all docs
db.< collectionName >.findOne( filterObject ) - to read one document
db.< collectionName >.countDocuments( filterObject ) - shows total number of documents.
filter Object : { fieldName : {operator: value}} fieldName : database fields name operator : $eq = equal , $gt= greater than, $lt : less than, $gte = greater than equal, $and and $or operator value : what value we are comparing with operator.
e.g { age : {$gt:5}}. - age is greater than value 5
Cursor functions : These are applied to find() query .
sort( {fieldName: 1}) : 1 for ascending -1 for descending
limit( x ) : only gives x documents
UPDATE COMMANDS
db.< collectionName >.updateOne( filterObject, updateObject, options )
update Objects = { $set : {field: value}}
options : {upsert: true}
Upsert : Update + Insert, when we want a new info to create a new obejcts if no existing object matches filter queries.
db.< collectionName >.replaceOne( filterObject, updateObject ) Overwrites other fields also which are not in updateObject.
DELETE COMMANDS
db.< collectionName >.deleteOne( filterObject )
Projection
Only return selected fields while returning result documents.
db.< collectionName >.find( filterObject, projectionObject ) e.g. {name:1, age:1, id:0} - only show name and age and don't show id
MONGO ATLAS CLOUD SETUP : Check the video in tutorial
** Enviroment Variable** : To use environment variable we can use a npm package called dotenv which will create new process.env variables.
Install dotenv using npm install dotenv
just have use .env file in your root directory
and call require('dotenv').config()
Related Links/Videos
Mongo Atlas Setup Detailed Video
Chapter 7 - Mongoose and REST APIs
[[ Reading Material ]]
You can install mongoose using npm :
npm install mongoose
After installing , you can import mongoose to your project :
const mongoose = require("mongoose");
Connection to Database
To connect mongoose to your database test, you have to use the following commands :
var mongoose = require('mongoose');
await mongoose.connect('mongodb://127.0.0.1:27017/test');
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
Schema
Schema is the specification according to which data object is created in Database.
taskSchema which contains title, status, date fields. So every task object saved in database will have these 3 fields according to Schema given
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const taskSchema = new Schema({
title: String,
status: Boolean,
date: { type: Date, default: Date.now }
});
Many types of data are allowed in Mongoose Schema. The common SchemaTypes are:
String
Number
Date
Boolean
Mixed
ObjectId
Array
You can put a lot of conditions inside the Schema object :
age: { type: Number, default:18, min: 18, max: 65, required :true }
// default value of Number is 18 and should be between 18-65, and can't be null or empty
Detailed information on SchemaTypes is Here
Model
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.
const mongoose = require('mongoose');
const { Schema } = mongoose;
const taskSchema = new Schema({
title: String,
status: Boolean,
date: { type: Date, default: Date.now },
});
const Task = mongoose.model('Task', taskSchema); //Task Model to create new database objects for `tasks` Collection
Task 1
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.
Creata a Schema named taskSchema and model named Task as shown above.
CRUD in Mongoose
Create - new objects
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)
server.post("/task",function(req,res){
let task = new Task();
task.title = "shopping";
task.status = true;
task.date = new Date();
task.save();
})
Task 2
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.
//request body :
{
"title" : "task1",
"status" : true,
"date" :'2010-05-30"
}
// response body should return the newly created object.
res.json(task);
Check using Mongo Compass/or Mongo Shell that new record in database is created. Also check name of collection. Is is tasks ?
Read objects
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.
server.get("/task/:name",function(req,res){
Task.findOne({name:req.params.name},function(err,doc){
console.log(doc) // this will contain db object
})
})
server.get("/tasks",function(req,res){
Task.find({},function(err,docs){
console.log(docs) // this is an array which contains all task objects
})
})
Task 3
You have to create an API Endpoint to type GET named /tasks. It will return all task available in collection tasks.
//request is GET so no data in body :
// response body should return the all db objects of collection tasks.
res.json(tasks);
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.
Update - existing objects
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.
There are generally 2 cases in update :
Updating all values and overwriting the object properties completely.
Updating only few values by setting their new values.
First scenario is covered using this query. Here you are overwriting all properties and resulting object will only have name property.
server.put("/task/:name",function(req,res){
Task.findOneAndReplace({name:req.params.name},{name:'YouStart'},{new:true},function(err,doc){
console.log(doc) // this will contain new db object
})
})
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.
server.put("/task/:name",function(req,res){
Task.findOneAndUpdate({name:req.params.name},{name:'YouStart'},,{new:true},function(err,doc){
console.log(doc) // this will contain db object
})
})
Task 4
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.
//request params will have id in URL path :
{
"title" : "task-changed",
}
// response body should return the newly updated object.
res.json(task);
Check using Mongo Compass/or Mongo Shell that only title of record in database is changed. All other properties remain the same.
Delete - existing objects
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.
server.delete("/task/:name",function(req,res){
Task.findOneAndDelete({name:req.params.name},function(err,doc){
console.log(doc) // this will contain deleted object object
})
})
Task 5
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.
//request params will have id in URL path :
// response body should return the deleted object.
res.json(task);
Check using Mongo Compass/or Mongo Shell that the record is deleted or not.
[[ Chapter Notes ]]
install mongoose npm install mongoose
Mongoose connection code
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/test');
// use `await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test');` if your database has auth enabled
}
Mongoose Schema : Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
const productSchema = new Schema({
title: {type: String, required: true, unique: true} ,
description: String,
price: {type: Number, min:[0,'wrong price'],required: true},
discountPercentage: {type: Number, min:[0,'wrong min discount'], max:[50,'wrong max discount']},
rating: {type: Number, min:[0,'wrong min rating'], max:[5,'wrong max rating']},
brand: {type: String,required: true},
category: {type: String, required: true},
thumbnail: {type: String, required: true},
images: [ String ]
});
Mongoose Model : model are built using a combination of Schema and name of Collection.
const Product = mongoose.model('Product', productSchema);
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.
const document = new Product();
// document is actually saved in database after save()
await document.save();
Mongoose Schema/Model can act as Model of Model-View-Controller concept.
CRUD API and mongoose methods
CREATE :
create product - use **POST ** HTTP Method
const product = new Product();
await product.save()
READ :
read all products - use GET HTTP Method
const products = await Product.find();
const products = await Product.find({price:{$gt:500}});
read 1 product - use GET HTTP Method
const product = await Product.findById(id);
UPDATE :
replace product fields (all fields) - use PUT HTTP Method
const doc = await Product.findOneAndReplace({_id:id},req.body,{new:true})
update only some product fields - use PATCH HTTP Method
const doc = await Product.findOneAndUpdate({_id:id},req.body,{new:true})
DELETE :
delete 1 product - use DELETE HTTP Method
const doc = await Product.findOneAndDelete({_id:id})
[[ Assignments ]]
Assignment 1 : Make a Schema for user with userSchema which has these conditions :
firstName is required, maximum length 16 chars
lastName is not required, maximum length 16 chars
age is a Number, minimum value 12, maximum 100
email make a validator of email, as given in mongoose documentation.
address make address a nested data structure which has its own Schema [ AddressSchema ??] [ Hint: check mongoose documentation for sub-documents to do it
Create addressSchema needed in above example as :
pincode : Number, required
street : String, required
phone: String, length=10
Now try to create this user object and save it to database.
What happens to addresses ? How address document is stored ? check if it creates a new collection in database
What happens if you don't provide validated data in any field. [Note: Throw proper errors strings ]
Related Links/Videos
Queries in Mongoose : Link
Chapter 8 - React Integration and MERN Stack Live deployment
[[ Chapter Notes ]]
Sending data from front-end to Server
Fetch : it is in-built API in the browser
Axios : we will use axios as it is easier to use.
CORS Issues :
CORS - Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy
we will use CORS package to allow cross origin request from React JS server to NodeJS server as they are on different hosts.
npm install cors
to use cors -
const cors = require('cors');
server.use(cors())
HTML Forms
name attribute on input elements is used to send data keys which are validated with schema in backend.
Build a React Project :
Run npm run build
use build folder to be hosted on public hosting/static hosting
Host a React Project :
you can use build folder of react and add it to static hosting of express. server.use(express.static('build'));
Use Routing in Front-end
use wildcard in express route to point to React single page applications (index.html)