├── .gitignore
├── 00. Complete Notes.md
├── 01_What_is_NodeJS
└── Learning.md
├── 02_Node_JS_Installation
└── Learning.md
├── 04_Modules_in_NodeJS
├── math.js
├── module.js
└── package.json
├── 05_File_Handling_in_NodeJS
├── contacts.txt
├── file.js
├── package.json
└── test.txt
├── 06_How_NodeJS_Works
├── blocking.png
├── contacts.txt
├── file.js
├── learning.md
├── non-blocking.png
└── package.json
├── 07_Building_HTTP_Server
├── index.js
├── log.txt
└── package.json
├── 08_Handling_URL
├── Learning.md
├── index.js
├── log.txt
├── package-lock.json
└── package.json
├── 09_HTTP_Methods
├── Learnings.md
├── index.js
├── log.txt
├── package-lock.json
└── package.json
├── 10_Getting_Started_with_Express_and_Nodejs
├── index.js
├── log.txt
├── package-lock.json
└── package.json
├── 11_How_Versioning_Works_in_NodeJS
├── Learnings.md
├── package-lock.json
└── package.json
├── 12_What_is_REST_API
├── 1.png
├── 2.png
├── 3.png
├── 4.png
└── Learnings.md
├── 13_Building_REST_API_using_Node_and_Express
├── MOCK_DATA.json
├── index.js
├── package-lock.json
├── package.json
└── task.md
├── 14_Intro_to_POSTMAN_for_REST_API
├── MOCK_DATA.json
├── index.js
├── package-lock.json
└── package.json
├── 15_Express_Middleware
├── MOCK_DATA.json
├── Readme.md
├── index.js
├── log.txt
├── package-lock.json
└── package.json
├── 16_What_are_HTTP_Headers_in_API
├── MOCK_DATA.json
├── Readme.md
├── img1.png
├── img2.png
├── index.js
├── log.txt
├── package-lock.json
└── package.json
├── 17_HTTP_Status_Codes
├── MOCK_DATA.json
├── Readme.md
├── index.js
├── package-lock.json
└── package.json
├── 18_Getting_Started_with_MongoDB
└── Readme.md
├── 19_Connecting_NodeJS_with_MongoDB
├── MOCK_DATA.json
├── Readme.md
├── index.js
├── package-lock.json
└── package.json
├── 20_Model_View_Controller_in_NodeJS
├── Readme.md
├── connection.js
├── controllers
│ └── user.js
├── index.js
├── log.txt
├── middlewares
│ └── index.js
├── models
│ └── user.js
├── package-lock.json
├── package.json
└── routes
│ └── user.js
├── 21_Custom_URL_Shortener
├── connect.js
├── controllers
│ └── url.js
├── index.js
├── models
│ └── url.js
├── package-lock.json
├── package.json
└── routes
│ └── url.js
├── 22_Server_Side_Rendering_with_EJS_and_NodeJS
├── Readme.md
├── connect.js
├── controllers
│ └── url.js
├── index.js
├── models
│ └── url.js
├── package-lock.json
├── package.json
├── routes
│ ├── staticRoute.js
│ └── url.js
└── views
│ └── home.ejs
├── 23_Building_Node.js_Authentication_from_Scratch
├── Readme.md
├── connect.js
├── controllers
│ ├── url.js
│ └── user.js
├── images
│ ├── expressflow.png
│ └── stateful.png
├── index.js
├── middlewares
│ └── auth.js
├── models
│ ├── url.js
│ └── user.js
├── package-lock.json
├── package.json
├── routes
│ ├── staticRoute.js
│ ├── url.js
│ └── user.js
├── service
│ └── auth.js
└── views
│ ├── home.ejs
│ ├── login.ejs
│ └── signup.ejs
├── 24_JWT_Authentication_in_NodeJS
├── Readme.md
├── connect.js
├── controllers
│ ├── url.js
│ └── user.js
├── images
│ ├── expressflow.png
│ └── stateful.png
├── index.js
├── middlewares
│ └── auth.js
├── models
│ ├── url.js
│ └── user.js
├── package-lock.json
├── package.json
├── routes
│ ├── staticRoute.js
│ ├── url.js
│ └── user.js
├── service
│ └── auth.js
└── views
│ ├── home.ejs
│ ├── login.ejs
│ └── signup.ejs
├── 25_What_are_Cookies_in_NodeJS
├── Readme.md
├── connect.js
├── controllers
│ ├── url.js
│ └── user.js
├── index.js
├── middlewares
│ └── auth.js
├── models
│ ├── url.js
│ └── user.js
├── package-lock.json
├── package.json
├── routes
│ ├── staticRoute.js
│ ├── url.js
│ └── user.js
├── service
│ └── auth.js
└── views
│ ├── home.ejs
│ ├── login.ejs
│ └── signup.ejs
├── 26_Authorization_in_NodeJS
├── Readme.md
├── connect.js
├── controllers
│ ├── url.js
│ └── user.js
├── index.js
├── middlewares
│ └── auth.js
├── models
│ ├── url.js
│ └── user.js
├── package-lock.json
├── package.json
├── routes
│ ├── staticRoute.js
│ ├── url.js
│ └── user.js
├── service
│ └── auth.js
└── views
│ ├── home.ejs
│ ├── login.ejs
│ └── signup.ejs
├── 27_Creating_Discord_Bot_in_NodeJS
├── command.js
├── index.js
├── package-lock.json
└── package.json
├── 28_Uploding_Files_with_NodeJS_and_Multer
├── Readme.md
├── index.js
├── package-lock.json
├── package.json
├── uploads
│ └── 1712197245796-github (2).png
└── views
│ └── homepage.ejs
├── 29_Setting_Up_Project-NodeJS_Blogging_App
├── Readme.md
├── index.js
├── models
│ └── user.js
├── package-lock.json
├── package.json
├── public
│ └── images
│ │ └── deafult.jpg
├── routes
│ └── user.js
└── views
│ ├── home.ejs
│ ├── partials
│ ├── head.ejs
│ ├── nav.ejs
│ └── scripts.ejs
│ ├── signin.ejs
│ └── signup.ejs
├── 30_Setting_up_Authentication-NodeJS_Blogging_App
├── Readme.md
├── index.js
├── middlewares
│ └── authentication.js
├── models
│ ├── blog.js
│ └── user.js
├── package-lock.json
├── package.json
├── public
│ ├── images
│ │ └── deafult.jpg
│ └── uploads
│ │ ├── 1712311193510-Screenshot (1).png
│ │ └── 1712311768043-Screenshot (1).png
├── routes
│ ├── blog.js
│ └── user.js
├── services
│ └── authentication.js
└── views
│ ├── addBlog.ejs
│ ├── home.ejs
│ ├── partials
│ ├── head.ejs
│ ├── nav.ejs
│ └── scripts.ejs
│ ├── signin.ejs
│ └── signup.ejs
├── 31_Complete_Blog_App
├── Readme.md
├── index.js
├── middlewares
│ └── authentication.js
├── models
│ ├── blog.js
│ ├── comments.js
│ └── user.js
├── package-lock.json
├── package.json
├── public
│ ├── images
│ │ └── default.png
│ └── uploads
│ │ ├── 1712311193510-Screenshot (1).png
│ │ ├── 1712311768043-Screenshot (1).png
│ │ ├── 1712428496751-1_A7PQiIdB5buNa0mgq063Xg.png
│ │ ├── 1712429054876-piyu.avif
│ │ └── 1712429113684-fire.avif
├── routes
│ ├── blog.js
│ └── user.js
├── services
│ └── authentication.js
└── views
│ ├── addBlog.ejs
│ ├── blog.ejs
│ ├── home.ejs
│ ├── partials
│ ├── head.ejs
│ ├── nav.ejs
│ └── scripts.ejs
│ ├── signin.ejs
│ └── signup.ejs
├── 32_Deploy_NodeJS_App_on_Cloud
├── .env
├── Readme.md
├── app.js
├── middlewares
│ └── authentication.js
├── models
│ ├── blog.js
│ ├── comments.js
│ └── user.js
├── package-lock.json
├── package.json
├── public
│ ├── images
│ │ └── default.png
│ └── uploads
│ │ ├── 1712311193510-Screenshot (1).png
│ │ ├── 1712311768043-Screenshot (1).png
│ │ ├── 1712428496751-1_A7PQiIdB5buNa0mgq063Xg.png
│ │ ├── 1712429054876-piyu.avif
│ │ └── 1712429113684-fire.avif
├── routes
│ ├── blog.js
│ └── user.js
├── services
│ └── authentication.js
└── views
│ ├── addBlog.ejs
│ ├── blog.ejs
│ ├── home.ejs
│ ├── partials
│ ├── head.ejs
│ ├── nav.ejs
│ └── scripts.ejs
│ ├── signin.ejs
│ └── signup.ejs
├── 33_WebSocket
├── Readme.md
├── index.js
├── package-lock.json
├── package.json
└── public
│ └── index.html
├── 34_Streams
├── 20M.txt
├── Readme.md
├── index.js
├── package-lock.json
└── package.json
├── 35_Scale_NodeJS_App_using_Cluster_module
├── Readme.md
├── app.js
├── cluster.js
├── package-lock.json
└── package.json
├── 36_What_is_Nginx
└── Readme.md
├── 37_Install_&_Setup_Nginx
└── Readme.md
├── 42_GraphQL_NodeJS
├── Readme.md
├── client
│ ├── .gitignore
│ ├── README.md
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ ├── logo192.png
│ │ ├── logo512.png
│ │ ├── manifest.json
│ │ └── robots.txt
│ └── src
│ │ ├── App.css
│ │ ├── App.js
│ │ ├── App.test.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── logo.svg
│ │ ├── reportWebVitals.js
│ │ └── setupTests.js
└── server
│ ├── index.js
│ ├── package-lock.json
│ └── package.json
├── 43_Threads_App_GraphQL_Clone
└── Readme.md
└── Readme.md
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/01_What_is_NodeJS/Learning.md:
--------------------------------------------------------------------------------
1 | Javascript code executes inside browser.
2 |
3 | Browser has javascript engine which executes the javascript code.
4 |
5 | Javascript Engine presents only inside Browser.
6 |
7 | Each broswer has different Javascript engines.
8 |
9 | ```
10 | Chrome -> V8 Engine
11 | Fierfox -> Spider Monkey
12 | Safari -> Nitro
13 | ```
14 |
15 | The most populor engine is V8 engine.
16 |
17 | A scientist Ryan Dahl taken the V8 engine and embedded with C++ code.And named this project as `NodeJS`.
18 |
19 | Now In NodeJS (Benefit)
20 | ---
21 |
22 | - You can run JS outside of the browser.
23 | - Javascript can talk to native machine beacause of C++.
24 | - You can create webservers in Javascript language.
25 |
26 | ## What is NodeJS?
27 |
28 | NodeJs is neither a framework or language . NodeJS is a Runtime Environment for javascript.
29 |
30 | Ex:
31 | ```javascript
32 | PS C:\Users\ayush> node
33 | Welcome to Node.js v20.10.0.
34 | Type ".help" for more information.
35 | > console.log("Hello");
36 | Hello
37 | undefined
38 | > 2+2
39 | 4
40 | >
41 |
42 | ```
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/02_Node_JS_Installation/Learning.md:
--------------------------------------------------------------------------------
1 | # Steps to Install NodeJS
2 |
3 | 1. Go to official website `nodejs.org`
4 |
5 | 2. Select LTS Version of NodeJS.
6 | LTS - Long Term Support , Start with even number (Stable realese - can be used in production)
7 |
8 | Beta(Current) - Bugs , Unstability , start with odd number
9 |
10 | 3. Intall in your local computer and add the path `C:\Program Files\nodejs` to your environment variable.
11 |
12 | 4. Open Terminal and write command
13 |
14 | ```javascript
15 | PS C:\Users\ayush> node --version
16 | v20.10.0
17 | PS C:\Users\ayush>
18 | ```
19 |
20 | 5. If giving this output then NodeJS Installed Succesfully.
21 |
22 | # What is npm ?
23 |
24 | NPM -> Node Package Manager. We can manage package through it.
--------------------------------------------------------------------------------
/04_Modules_in_NodeJS/math.js:
--------------------------------------------------------------------------------
1 |
2 | function add(a , b){
3 | return a + b
4 | }
5 |
6 | function sub(a , b){
7 | return a - b;
8 | }
9 |
10 | // module.exports = add;
11 | // module.exports = sub ; // overiding the value
12 |
13 | // we can use object to export multiple values
14 |
15 |
16 |
17 | // multi exports
18 | module.exports = {
19 | add ,
20 | sub,
21 | }
22 |
23 |
24 | //exporting anonymous function
25 | // exports.add = (a , b) => a + b;
26 |
27 | // exports.sub = ( a , b) => a - b;
--------------------------------------------------------------------------------
/04_Modules_in_NodeJS/module.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Split your code into different files and folders.
3 | * All maths related function will be written in math.js
4 | *
5 | * To use the math.js file in other file
6 | * --------------------------------------
7 | * use require -> const name = require('filename')
8 | *
9 | */
10 |
11 | const buffer = require('buffer') // built in package
12 |
13 | const math = require('./math')
14 |
15 | //De-structuring -> we can directlly use add and sub function
16 | const {add , sub } = require('./math')
17 |
18 | console.log("Math Add value is : ",math.add(2 , 4));
19 | console.log("Math Subtract value is : ",math.sub(2 , 4));
20 |
21 | console.log("\nUsing destructured function \n")
22 |
23 | console.log("Math Add value is : ",add(2 , 4));
24 | console.log("Math Subtract value is : ",sub(2 , 4));
25 |
26 |
--------------------------------------------------------------------------------
/04_Modules_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "4_modules_in_nodejs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "module.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start":"node module.js"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/05_File_Handling_in_NodeJS/contacts.txt:
--------------------------------------------------------------------------------
1 | Ayush Kumar: +91 8238283828
2 | Jone Doe : +91 9222222222
--------------------------------------------------------------------------------
/05_File_Handling_in_NodeJS/file.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 |
3 | //used this fs module to intract with files
4 |
5 | //creating a file (Synchronous call)
6 | // fs.writeFileSync("./test.txt" , 'Hey There');
7 |
8 | //Async
9 | // fs.writeFile("./test.txt" , "Hello World", (err) => {})
10 |
11 |
12 | //Reading the file
13 |
14 | // Sync.. -> returns the result
15 | // const result = fs.readFileSync("./contacts.txt" , "utf-8");
16 | // console.log(result);
17 |
18 | //Async.. -> return nothing , we have to pass a callback
19 | // fs.readFile("./contacts.txt" , "utf-8" , (err , result)=>{
20 | // if(err){
21 | // console.log("Error",err);
22 | // }else{
23 | // console.log(result);
24 | // }
25 | // });
26 |
27 |
28 | // Appending the text
29 | // fs.appendFileSync("./test.txt" , "\nHey there I am appended");
30 |
31 |
32 | // Copy the file
33 | // fs.cpSync("./test.txt" , "./copy.txt");
34 |
35 | // Delete the file
36 | // fs.unlinkSync("./copy.txt");
37 |
38 | // Cheking status of file
39 | // console.log(fs.statSync("./test.txt"));
40 |
41 | //making directory
42 | // fs.mkdirSync("my-docs");
43 | fs.mkdirSync("my-docs/a/b" , { recursive:true});
44 |
45 |
46 |
--------------------------------------------------------------------------------
/05_File_Handling_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "5_file_handling_in_nodejs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "file.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC"
11 | }
12 |
--------------------------------------------------------------------------------
/05_File_Handling_in_NodeJS/test.txt:
--------------------------------------------------------------------------------
1 | Hello World27
2 | Hey there I am appended
3 | Hey there I am appended
--------------------------------------------------------------------------------
/06_How_NodeJS_Works/blocking.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/06_How_NodeJS_Works/blocking.png
--------------------------------------------------------------------------------
/06_How_NodeJS_Works/contacts.txt:
--------------------------------------------------------------------------------
1 | Ayush Kumar: +91 8238283828
2 | Jone Doe : +91 9222222222
--------------------------------------------------------------------------------
/06_How_NodeJS_Works/file.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 | const os = require('os')
3 |
4 | //gives the computer information
5 | console.log(os.cpus().length);
6 |
7 |
8 | // Sync.. Blocking ..
9 |
10 | console.log("1");
11 |
12 | const result = fs.readFileSync('contacts.txt' , 'utf-8');
13 | console.log(result);
14 |
15 | console.log("2");
16 |
17 |
18 | // Async.. Non-Blocking
19 |
20 | console.log("\nNon-Blocking(Async) \n")
21 |
22 | console.log("1");
23 |
24 | fs.readFile('contacts.txt' , 'utf-8' , (err , result)=>{
25 | console.log(result);
26 | })
27 |
28 | console.log("2");
29 | console.log("3");
30 | console.log("4");
--------------------------------------------------------------------------------
/06_How_NodeJS_Works/learning.md:
--------------------------------------------------------------------------------
1 | ```
2 | Client ----------> Server
3 | Request (NodeJs)
4 | ```
5 |
6 | Request made to server. Node js has event queue.
7 |
8 | Firstly requests are queued into event queue .
9 |
10 | Now even loop is a machine which always watches the event queue.
11 |
12 | If event loop get any request in event queue the select that request using fifo(first in first out) principle.
13 |
14 | Request can be of two types :
15 |
16 | 1. Blocking Operations (Sync.. task)
17 | 3. Non- Blockinng Operations (Async.. task)
18 |
19 | If the request has `non-blocking operation` then the server process it and sends the response back to the user.
20 |
21 | 
22 |
23 | If the request has `blocking operation` then to resolve this request it goes to thread pool.
24 |
25 | Thread pool is a pool of threads . Threads act a worker which work for you . It is resposible for fuilful your blocking operation. If the works completes then it return the result . Then the respose is send back to the user .
26 |
27 | 
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/06_How_NodeJS_Works/non-blocking.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/06_How_NodeJS_Works/non-blocking.png
--------------------------------------------------------------------------------
/06_How_NodeJS_Works/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "5_file_handling_in_nodejs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "file.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC"
11 | }
12 |
--------------------------------------------------------------------------------
/07_Building_HTTP_Server/index.js:
--------------------------------------------------------------------------------
1 | const http = require("http");
2 | const fs = require("fs");
3 |
4 | const myServer = http.createServer((req , res)=>{
5 |
6 | const log = `${Date.now()} : ${req.url} : New Request Recieved \n`;
7 | fs.appendFile('log.txt' , log , (err , data)=>{
8 |
9 | switch(req.url){
10 | case '/' : res.end("Home Page");
11 | break;
12 |
13 | case '/about' : res.end("I am Ayush");
14 | break;
15 |
16 | default:
17 | res.end("404 Not Found")
18 |
19 | }
20 |
21 |
22 | })
23 |
24 |
25 | // console.log(req.headers)
26 | // console.log(req)
27 |
28 |
29 | });
30 |
31 | const PORT = 8000;
32 | myServer.listen(8000, ()=>{
33 | console.log(`Server started at port no ${PORT} `);
34 | })
35 |
36 |
--------------------------------------------------------------------------------
/07_Building_HTTP_Server/log.txt:
--------------------------------------------------------------------------------
1 | 1709126389288 : New Request Recieved
2 | 1709126389582 : New Request Recieved
3 | 1709126402207 : New Request Recieved
4 | 1709126402351 : New Request Recieved
5 | 1709126410765 : New Request Recieved
6 | 1709126410941 : New Request Recieved
7 | 1709126501780 : New Request Recieved
8 | 1709126501991 : New Request Recieved
9 | 1709126516561 : / : New Request Recieved
10 | 1709126516662 : /favicon.ico : New Request Recieved
11 | 1709126528727 : /about : New Request Recieved
12 | 1709126528831 : /favicon.ico : New Request Recieved
13 | 1709126559937 : /contactus : New Request Recieved
14 | 1709126560124 : /favicon.ico : New Request Recieved
15 | 1709126684112 : /contactus : New Request Recieved
16 | 1709126684220 : /favicon.ico : New Request Recieved
17 | 1709126687361 : / : New Request Recieved
18 | 1709126687456 : /favicon.ico : New Request Recieved
19 | 1709126693949 : /about : New Request Recieved
20 | 1709126694048 : /favicon.ico : New Request Recieved
21 |
--------------------------------------------------------------------------------
/07_Building_HTTP_Server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "7_building_http_server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node index",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC"
12 | }
13 |
--------------------------------------------------------------------------------
/08_Handling_URL/Learning.md:
--------------------------------------------------------------------------------
1 | # URL
2 | Uniform Resource Locator
3 |
4 | ```
5 | https:// www.ayush.dev/
6 | -------- --------------
7 | Protocol Domain - User friendly name
8 | of IP Address of My Server
9 |
10 | dev/ -> Path
11 | ayush.dev/project/1 -> Nested Path
12 |
13 | ayush.dev/about?userID=1&a=2 -> Query parameter
14 |
15 | ```
16 |
17 | Protocol: Set of rules that tells browser how to communicate to the browser.
18 |
19 | https -> Hypertext Transfer Protocol Secure
20 |
21 |
--------------------------------------------------------------------------------
/08_Handling_URL/index.js:
--------------------------------------------------------------------------------
1 | const http = require("http");
2 | const fs = require("fs");
3 | const url = require("url");
4 |
5 | const myServer = http.createServer((req , res)=>{
6 |
7 | if(req.url === '/favicon.ico') return res.end();
8 |
9 |
10 | const log = `${Date.now()} : ${req.url} : New Request Recieved \n`;
11 | const myUrl = url.parse(req.url , true);
12 | console.log(myUrl);
13 |
14 | fs.appendFile('log.txt' , log , (err , data)=>{
15 |
16 | switch(myUrl.pathname){
17 | case '/' : res.end("Home Page");
18 | break;
19 |
20 | case '/about' :
21 | //query parameter
22 | const username = myUrl.query.myname ;
23 | console.log(username)
24 | res.end(`Hii, ${username}`);
25 | break;
26 |
27 | case "/search":
28 | const search = myUrl.query.search_query;
29 | console.log(search)
30 | res.end("Here are your result for "+search);
31 | break;
32 |
33 | default:
34 | res.end("404 Not Found")
35 |
36 | }
37 |
38 |
39 | })
40 |
41 |
42 | // console.log(req.headers)
43 | // console.log(req)
44 |
45 |
46 | });
47 |
48 | const PORT = 8000;
49 | myServer.listen(8000, ()=>{
50 | console.log(`Server started at port no ${PORT} `);
51 | })
52 |
53 |
--------------------------------------------------------------------------------
/08_Handling_URL/log.txt:
--------------------------------------------------------------------------------
1 | 1709129047044 : / : New Request Recieved
2 | 1709129073528 : /about : New Request Recieved
3 | 1709129148969 : /about? : New Request Recieved
4 | 1709129174894 : /about?myname=Ayush : New Request Recieved
5 | 1709129456962 : /about?myname=Ayush : New Request Recieved
6 | 1709129715248 : /about?myname=Ayush : New Request Recieved
7 | 1709129744591 : /about?myname=Ayush&userid=1 : New Request Recieved
8 | 1709129821573 : /about?myname=Ayush&userid=1 : New Request Recieved
9 | 1709129828388 : /about?myname=Ayush : New Request Recieved
10 | 1709129853737 : /about?myname=Ayush : New Request Recieved
11 | 1709129900258 : /about : New Request Recieved
12 | 1709129906871 : /about?myname=Ayush : New Request Recieved
13 | 1709129911244 : /about/?myname=Ayush : New Request Recieved
14 | 1709129975789 : /about/?myname=Ayush : New Request Recieved
15 | 1709130026368 : / : New Request Recieved
16 | 1709130035112 : /about : New Request Recieved
17 | 1709130048246 : /about?myname=Ayush : New Request Recieved
18 | 1709130055907 : /about?myname=Ayush : New Request Recieved
19 | 1709130141940 : /about?myname=Ayush : New Request Recieved
20 | 1709130151391 : /about : New Request Recieved
21 | 1709130162145 : /about?myname=Ayush : New Request Recieved
22 | 1709130290638 : / : New Request Recieved
23 | 1709130306635 : /search_query=ayush : New Request Recieved
24 | 1709130336662 : /search/search_query=ayush : New Request Recieved
25 | 1709130441084 : /search/search_query=ayush : New Request Recieved
26 | 1709130450412 : / : New Request Recieved
27 | 1709130461413 : /search?search_query=ayush : New Request Recieved
28 | 1709130679041 : /search?search_query=ayush : New Request Recieved
29 | 1709130718820 : /search?search_query=ayush : New Request Recieved
30 | 1709130841622 : /search?search_query=ayush : New Request Recieved
31 | 1709130849090 : /search?search_query=ayush : New Request Recieved
32 | 1709130861890 : /search? : New Request Recieved
33 | 1709130864537 : /search? : New Request Recieved
34 | 1709130867377 : /search : New Request Recieved
35 | 1709130881093 : /search/search_query=Ayushasn : New Request Recieved
36 |
--------------------------------------------------------------------------------
/08_Handling_URL/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "7_building_http_server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node index",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "url": "^0.11.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/09_HTTP_Methods/Learnings.md:
--------------------------------------------------------------------------------
1 | # HTTP Methods
2 | ```
3 | GET -> When you want to get some data from the server.
4 |
5 | POST -> When you want to send and mutate some data in server.
6 |
7 | PUT
8 | PATCH
9 | DELETE
10 | ```
--------------------------------------------------------------------------------
/09_HTTP_Methods/index.js:
--------------------------------------------------------------------------------
1 | const http = require("http");
2 | const fs = require("fs");
3 | const url = require("url");
4 |
5 | const myServer = http.createServer((req , res)=>{
6 |
7 | if(req.url === '/favicon.ico') return res.end();
8 |
9 |
10 | const log = `${Date.now()} : ${req.url} : New Request Recieved \n`;
11 | const myUrl = url.parse(req.url , true);
12 | console.log(myUrl);
13 |
14 | fs.appendFile('log.txt' , log , (err , data)=>{
15 |
16 | switch(myUrl.pathname){
17 |
18 | case '/' :
19 |
20 | if(req.method == 'GET') res.end("Home Page");
21 | break;
22 |
23 | case '/about' :
24 | //query parameter
25 | const username = myUrl.query.myname ;
26 | console.log(username)
27 | res.end(`Hii, ${username}`);
28 | break;
29 |
30 | case "/search":
31 | const search = myUrl.query.search_query;
32 | console.log(search)
33 | res.end("Here are your result for "+search);
34 | break;
35 |
36 | case '/signup':
37 |
38 | if(req.method == 'GET') res.end("This is a signup From");
39 | else if(req.method == "POST"){
40 | //DB Query
41 | res.end("Success");
42 | }
43 | break;
44 | default:
45 | res.end("404 Not Found")
46 |
47 | }
48 |
49 |
50 | })
51 |
52 |
53 | // console.log(req.headers)
54 | // console.log(req)
55 |
56 |
57 | });
58 |
59 | const PORT = 8000;
60 | myServer.listen(8000, ()=>{
61 | console.log(`Server started at port no ${PORT} `);
62 | })
63 |
64 |
--------------------------------------------------------------------------------
/09_HTTP_Methods/log.txt:
--------------------------------------------------------------------------------
1 | 1709226120135 : / : New Request Recieved
2 | 1709226126979 : /signup : New Request Recieved
3 | 1709226163929 : /signup : New Request Recieved
4 | 1709226164361 : /signup : New Request Recieved
5 |
--------------------------------------------------------------------------------
/09_HTTP_Methods/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "7_building_http_server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node index",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "url": "^0.11.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/10_Getting_Started_with_Express_and_Nodejs/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express")
2 |
3 | const app = express();
4 |
5 | app.get('/',(req , res)=>{
6 | return res.send("Hello from Home Page")
7 | });
8 |
9 | app.get('/about' , (req , res)=>{
10 | return res.send(`Hello ${req.query.name}`)
11 | })
12 |
13 | const PORT = 8000;
14 | app.listen(8000, ()=>{
15 | console.log(`Server started at port no ${PORT} `);
16 | })
17 |
18 |
--------------------------------------------------------------------------------
/10_Getting_Started_with_Express_and_Nodejs/log.txt:
--------------------------------------------------------------------------------
1 | 1709227219573 : / : New Request Recieved
2 |
--------------------------------------------------------------------------------
/10_Getting_Started_with_Express_and_Nodejs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "7_building_http_server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node index",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/11_How_Versioning_Works_in_NodeJS/Learnings.md:
--------------------------------------------------------------------------------
1 | # Version
2 |
3 | 4.18.2
4 |
5 | 1st Part -> 4
6 | 2nd Part -> 18
7 | 3rd Part -> 2
8 |
9 | 3rd part(Last Part) - Miner Fixes (Optional)
10 | Latest -> 4.18.3
11 |
12 | 2nd Part - Recommended Bug Fix (Security)
13 | Latest -> 4.19.1
14 |
15 | 3rd Part -> Major Realese -> Major / Breaking Update
16 | Latest -> 5.0.1
17 |
18 | ---
19 |
20 | "express": "^4.18.3"
21 |
22 | ^4.18.3 | ^4.18.3 -> 5.0.0
23 |
24 | ^4.17.9
25 | ^4.18.1
26 | ^4.18.2
27 | ^4.18.3
28 | ..
29 | ^5.1.1 ❌
30 |
31 | ---
32 |
33 | ~4.18.1
34 | ~4.18.2
35 | ~4.18.3
36 | ~4.18.4
37 |
38 | ~4.19.1 ❌
39 |
--------------------------------------------------------------------------------
/11_How_Versioning_Works_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "11_how_versioning_works_in_nodejs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "express": "^4.18.3"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/12_What_is_REST_API/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/12_What_is_REST_API/1.png
--------------------------------------------------------------------------------
/12_What_is_REST_API/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/12_What_is_REST_API/2.png
--------------------------------------------------------------------------------
/12_What_is_REST_API/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/12_What_is_REST_API/3.png
--------------------------------------------------------------------------------
/12_What_is_REST_API/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/12_What_is_REST_API/4.png
--------------------------------------------------------------------------------
/12_What_is_REST_API/Learnings.md:
--------------------------------------------------------------------------------
1 | # Restfull API Rules
2 |
3 | 1. Works on server client architecture.
4 |
5 |
6 |
7 | 
8 |
9 | 2. Always Respect All Http methods.
10 | Get , Post , Put , Delete
11 |
12 | Get /user - user data read kro and return kro
13 |
14 | Post /user - handle new user creation
15 |
16 | Pathch /user - Update the user
17 |
18 |
19 |
20 | 
21 | 
22 | 
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/13_Building_REST_API_using_Node_and_Express/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const users = require("./MOCK_DATA.json")
3 |
4 | const app = express();
5 | const PORT = 8000;
6 |
7 | //Routes
8 | app.get('/users', (req, res)=>{
9 | const html = `
10 |
11 | ${users.map(user => `${user.first_name} `).join("")}
12 |
13 | `
14 | res.send(html)
15 | })
16 |
17 | //REST Api
18 |
19 | app.get('/api/users', (req, res)=>{
20 | return res.json(users);
21 | })
22 |
23 | app.route('/api/users/:id').get((req, res)=>{
24 |
25 | const id = Number(req.params.id);
26 | const user = users.find(user => user.id === id);
27 | return res.json(user);
28 |
29 | })
30 | .patch((req, res) =>{
31 | // TODO : edit the user with id
32 | return res.json({status : 'Pending'})
33 | })
34 | .delete((req , res)=>{
35 | // TODO : delete the user with id
36 | res.json({status : 'Pending'})
37 | })
38 |
39 |
40 |
41 | // app.post('/api/users' , (req , res)=>{
42 | // // TODO : Create new user
43 | // return res.json({status: "pending"});
44 | // })
45 |
46 | // app.patch('/api/users/:id' , (req , res)=>{
47 | // // TODO : Edit the user with id
48 | // return res.json({status: "pending"});
49 | // })
50 |
51 | // app.delete('/api/users/:id' , (req , res)=>{
52 | // // TODO : delete the user with id
53 | // return res.json({status: "pending"});
54 | // })
55 |
56 | app.listen(PORT , ()=>{
57 | console.log(`Server started at Port ${PORT}`)
58 | })
--------------------------------------------------------------------------------
/13_Building_REST_API_using_Node_and_Express/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "13_building_rest_api_using_node_and_express",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/13_Building_REST_API_using_Node_and_Express/task.md:
--------------------------------------------------------------------------------
1 | # Rest API - JSON
2 |
3 | GET /users - HTML Document render - Done
4 | GET /api/users - List all users - Done
5 |
6 | GET /api/users/1 - Get the user with ID 1 - Done
7 | GET /api/users/2 - Get the user with ID 2 - Done
8 |
9 | Dynamic Path Parameter
10 | GET /api/user/:id
11 | :id -> Variable | Dynamic - Done
12 |
13 | POST /api/users - Create new user
14 |
15 | PATCH /api/users/1 - Edit the user with ID 1
16 |
17 | DELETE /api/users/1 - Delete the user with ID 1
18 |
--------------------------------------------------------------------------------
/14_Intro_to_POSTMAN_for_REST_API/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const users = require("./MOCK_DATA.json")
3 | const fs = require("fs")
4 |
5 | const app = express();
6 | const PORT = 8000;
7 |
8 | //Middleware - Plugin
9 | app.use(express.urlencoded({extended:false}));
10 |
11 | //Routes
12 | app.get('/users', (req, res)=>{
13 | const html = `
14 |
15 | ${users.map(user => `${user.first_name} `).join("")}
16 |
17 | `
18 | res.send(html)
19 | })
20 |
21 | //REST Api
22 |
23 | app.get('/api/users', (req, res)=>{
24 | return res.json(users);
25 | })
26 |
27 | app.route('/api/users/:id').get((req, res)=>{
28 |
29 | const id = Number(req.params.id);
30 | const user = users.find(user => user.id === id);
31 | return res.json(user);
32 |
33 | })
34 | .patch((req, res) =>{
35 | // TODO : edit the user with id
36 | return res.json({status : 'Pending'})
37 | })
38 | .delete((req , res)=>{
39 | // TODO : delete the user with id
40 | res.json({status : 'Pending'})
41 | })
42 |
43 |
44 |
45 | app.post('/api/users' , (req , res)=>{
46 | // TODO : Create new user
47 | const body = req.body;
48 | users.push({...body , id:users.length+1});
49 | fs.writeFile('./MOCK_DATA.json', JSON.stringify(users), (err , data)=>{
50 | return res.json({status:"pending"});
51 | })
52 | console.log(body);
53 | return res.json({status: "sucess", id:users.length});
54 | });
55 |
56 | // app.patch('/api/users/:id' , (req , res)=>{
57 | // // TODO : Edit the user with id
58 | // return res.json({status: "pending"});
59 | // })
60 |
61 | // app.delete('/api/users/:id' , (req , res)=>{
62 | // // TODO : delete the user with id
63 | // return res.json({status: "pending"});
64 | // })
65 |
66 | app.listen(PORT , ()=>{
67 | console.log(`Server started at Port ${PORT}`)
68 | })
--------------------------------------------------------------------------------
/14_Intro_to_POSTMAN_for_REST_API/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "13_building_rest_api_using_node_and_express",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/15_Express_Middleware/Readme.md:
--------------------------------------------------------------------------------
1 | ## What is middleware?
2 |
3 | `Middleware` functions are functions that have access to the request object(req) , the response object(res), and the next middleware function in the application's requests-response cycle.
4 |
5 | The next middleware function commanly denoted by variable `next`.
6 |
7 | ### Middleware functions can perform:
8 |
9 | * Execute any code.
10 | * Make changes to the request and the response objects.
11 | * End the request-response cycle.
12 | * Call the next middleware function in the stack.
13 |
14 | If the current middleware is not functioning then it must call next middle ware otherwise request will be left hanging.
--------------------------------------------------------------------------------
/15_Express_Middleware/log.txt:
--------------------------------------------------------------------------------
1 | 1709389983537: GET : /users
2 | 1709390062567: GET : /api/users
3 | 1709390090126: GET : /api/users/id=123
4 | 1709390103569: GET : /api/users/123
5 | 1709390160883 : ::1 GET : /api/users/123
6 |
--------------------------------------------------------------------------------
/15_Express_Middleware/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "13_building_rest_api_using_node_and_express",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/16_What_are_HTTP_Headers_in_API/Readme.md:
--------------------------------------------------------------------------------
1 | # What are http Headers in API ?
2 |
3 | An HTTP header is a feild of an HTTP request or response that passes additional contex and metadata about the request or respose.
4 |
5 | 
6 |
7 | 
--------------------------------------------------------------------------------
/16_What_are_HTTP_Headers_in_API/img1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/16_What_are_HTTP_Headers_in_API/img1.png
--------------------------------------------------------------------------------
/16_What_are_HTTP_Headers_in_API/img2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/16_What_are_HTTP_Headers_in_API/img2.png
--------------------------------------------------------------------------------
/16_What_are_HTTP_Headers_in_API/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const users = require("./MOCK_DATA.json")
3 | const fs = require("fs");
4 | const path = require("path");
5 |
6 | const app = express();
7 | const PORT = 8000;
8 |
9 | //Middlewares
10 | app.use(express.urlencoded({extended:false}));
11 |
12 |
13 |
14 | //Routes
15 | app.get('/users', (req, res)=>{
16 | const html = `
17 |
18 | ${users.map(user => `${user.first_name} `).join("")}
19 |
20 | `
21 | res.send(html)
22 | })
23 |
24 | //REST Api
25 |
26 | app.get('/api/users', (req, res)=>{
27 | // res.setHeader("myName", "Ayush Kumar");
28 | res.setHeader("X-MyName", "Ayush Kumar"); //Custom header
29 | //Always add X to custum headers
30 | console.log(req.headers)
31 | return res.json(users);
32 | })
33 |
34 | app.route('/api/users/:id').get((req, res)=>{
35 |
36 | const id = Number(req.params.id);
37 | const user = users.find(user => user.id === id);
38 | return res.json(user);
39 |
40 | })
41 | .patch((req, res) =>{
42 | // TODO : edit the user with id
43 | return res.json({status : 'Pending'})
44 | })
45 | .delete((req , res)=>{
46 | // TODO : delete the user with id
47 | res.json({status : 'Pending'})
48 | })
49 |
50 |
51 |
52 | app.post('/api/users' , (req , res)=>{
53 | // TODO : Create new user
54 | const body = req.body;
55 | users.push({...body , id:users.length+1});
56 | fs.writeFile('./MOCK_DATA.json', JSON.stringify(users), (err , data)=>{
57 | return res.json({status:"pending"});
58 | })
59 | console.log(body);
60 | return res.json({status: "sucess", id:users.length});
61 | });
62 |
63 |
64 | app.listen(PORT , ()=>{
65 | console.log(`Server started at Port ${PORT}`)
66 | })
--------------------------------------------------------------------------------
/16_What_are_HTTP_Headers_in_API/log.txt:
--------------------------------------------------------------------------------
1 | 1709412832974 : ::1 GET : /
2 | 1709412833405 : ::1 GET : /
3 | 1709412874350 : ::1 GET : /api/users/123
4 | 1709413465517 : ::1 GET : /users
5 | 1709413502730 : ::1 GET : /users
6 | 1709413523425 : ::1 GET : /api/users
7 |
--------------------------------------------------------------------------------
/16_What_are_HTTP_Headers_in_API/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "13_building_rest_api_using_node_and_express",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/17_HTTP_Status_Codes/Readme.md:
--------------------------------------------------------------------------------
1 | # Status Code
2 |
3 | 404 - Not Found
4 |
5 | 1. Infromational responses ( 100-199 )
6 | 2. Successful responses ( 200-299 )
7 | - 201 - Created
8 | - 202 - Accepted
9 | - 203 - Non-Authoritative Infromation
10 | - 204 - Not Contnet
11 | - 205 - Reset Content
12 |
13 |
14 | 3. Redirection messages ( 300-399 )
15 | 4. Client error responses ( 400-499 )
16 | - 400 - Bad Request
17 | - 401 - Unauthorized
18 | - 402 - Payment Required
19 | - 403 - Forbidden
20 | - 404 - Not Found
21 | 5. Server error responses ( 500-599 )
22 | - 500 - Internal Server Error
23 | - 501 - Not Implemented
24 | - 502 - Bad Gateway
25 | - 503 - Service Unavailable
26 |
27 |
--------------------------------------------------------------------------------
/17_HTTP_Status_Codes/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const users = require("./MOCK_DATA.json")
3 | const fs = require("fs");
4 | const path = require("path");
5 |
6 | const app = express();
7 | const PORT = 8000;
8 |
9 | //Middlewares
10 | app.use(express.urlencoded({extended:false}));
11 |
12 |
13 |
14 | //Routes
15 | app.get('/users', (req, res)=>{
16 | const html = `
17 |
18 | ${users.map(user => `${user.first_name} `).join("")}
19 |
20 | `
21 | res.send(html)
22 | })
23 |
24 | //REST Api
25 |
26 | app.get('/api/users', (req, res)=>{
27 |
28 | console.log(req.headers)
29 | return res.json(users);
30 | })
31 |
32 | app.route('/api/users/:id').get((req, res)=>{
33 |
34 | const id = Number(req.params.id);
35 | const user = users.find(user => user.id === id);
36 |
37 | // 500 server error
38 | // const user = users.find(user => user[0].id === id);
39 |
40 | //If user not found - 404
41 | if(!user) return req.status(404).json({error : 'User Not found'});
42 | return res.json(user);
43 |
44 | })
45 |
46 | app.post('/api/users' , (req , res)=>{
47 | // TODO : Create new user
48 |
49 | const body = req.body;
50 | if(!body || !body.first_name || !body.last_name || !body.email || !body.gender || !body.job_title){
51 | return res.status(400).json({msg: 'ALl fields are required'});
52 | }
53 |
54 | users.push({...body , id:users.length+1});
55 | fs.writeFile('./MOCK_DATA.json', JSON.stringify(users), (err , data)=>{
56 | return res.json({status:"pending"});
57 | })
58 |
59 | //Status code 201
60 | return res.status(201).json({status: "sucess", id:users.length});
61 | });
62 |
63 |
64 | app.listen(PORT , ()=>{
65 | console.log(`Server started at Port ${PORT}`)
66 | })
--------------------------------------------------------------------------------
/17_HTTP_Status_Codes/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "13_building_rest_api_using_node_and_express",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3",
14 | "nodemon": "^3.1.0"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/18_Getting_Started_with_MongoDB/Readme.md:
--------------------------------------------------------------------------------
1 | # MongoDB
2 |
3 | No-SQL Document Based Database.
4 |
5 | Strong Support for Aggregation Pipes.
6 |
7 | Works on BSON format.
8 |
9 | Best for Node Applications.
10 |
11 | # Commands
12 |
13 | ```
14 | > show dbs
15 | > use
16 | > show collections
17 | > db.coll.find()
18 | > db.coll.insert()
19 |
20 | ```
--------------------------------------------------------------------------------
/19_Connecting_NodeJS_with_MongoDB/Readme.md:
--------------------------------------------------------------------------------
1 | # Mongoose
2 |
3 | 1. Schema - Define the Structure
4 | Schema - Model
5 | Using Model we do CRUD Operation
--------------------------------------------------------------------------------
/19_Connecting_NodeJS_with_MongoDB/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "13_building_rest_api_using_node_and_express",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3",
14 | "mongoose": "^8.2.1",
15 | "nodemon": "^3.1.0"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/Readme.md:
--------------------------------------------------------------------------------
1 | # Model View Controller
2 | ```
3 | Model View Controller
4 | ------------------------
5 | Model
6 | / \
7 | / \
8 | View Contoller
9 |
10 | ```
11 |
12 |
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/connection.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | async function connectMongoDb(url){
4 | return mongoose.connect(url)
5 |
6 | }
7 |
8 | module.exports = {
9 | connectMongoDb,
10 | };
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/controllers/user.js:
--------------------------------------------------------------------------------
1 | const User = require('../models/user')
2 | async function handleGetAllUsers(req , res){
3 | const allDbUsers = await User.find({});
4 | return res.json(allDbUsers);
5 | }
6 |
7 | async function handleGetUserById(req , res){
8 |
9 | const user = await User.findById(req.params.id)
10 | if(!user) return req.status(404).json({error : 'User Not found'});
11 | return res.json(user);
12 |
13 | }
14 |
15 | async function handleUpdateUserById(req , res){
16 | await User.findByIdAndUpdate(req.params.id ,{ lastName:"Changed" } );
17 | return res.json({status : "Success"});
18 | }
19 |
20 | async function handleDeleteUserById(req , res){
21 | await User.findByIdAndDelete(req.params.id);
22 | return res.json({status : "Delete Success"});
23 | }
24 |
25 | async function handleCreateNewUser(req , res){
26 |
27 | const body = req.body;
28 | if(!body || !body.first_name || !body.last_name || !body.email || !body.gender || !body.job_title){
29 | return res.status(400).json({msg: 'ALl fields are required'});
30 | }
31 |
32 |
33 | const result = await User.create({
34 | firstName : body.first_name,
35 | lastName : body.last_name,
36 | email: body.email,
37 | gender : body.gender,
38 | jobTitle: body.job_title
39 | });
40 |
41 | console.log("result" , result);
42 |
43 | return res.status(201).json({msg: "Success" , id:result._id })
44 | }
45 |
46 | module.exports ={
47 | handleGetAllUsers,
48 | handleGetUserById,
49 | handleUpdateUserById,
50 | handleDeleteUserById,
51 | handleCreateNewUser
52 | };
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 |
3 | const {connectMongoDb} = require('./connection')
4 | const {logReqRes} = require('./middlewares')
5 | const userRouter = require('./routes/user')
6 |
7 | const app = express();
8 | const PORT = 8000;
9 |
10 | //Connection
11 | connectMongoDb('mongodb://127.0.0.1:27017/learning')
12 | .then(()=> console.log("MongoDB Connected"))
13 | .catch((err) => console.log("Mongo Error" , err));
14 |
15 |
16 | //Middlewares
17 | app.use(express.urlencoded({extended:false}));
18 | app.use(logReqRes("log.txt"));
19 |
20 | //Route
21 | //express will match /api/users path and next path will give to the userRouter
22 | app.use("/api/users" , userRouter)
23 |
24 | app.listen(PORT , ()=>{
25 | console.log(`Server started at Port ${PORT}`)
26 | })
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/log.txt:
--------------------------------------------------------------------------------
1 | 1709817070268 : ::1 &{req.mentod} : /api/users/
2 | 1709817091419 : ::1 &{req.mentod} : /
3 | 1709817091967 : ::1 &{req.mentod} : /
4 | 1709817095220 : ::1 &{req.mentod} : /users
5 | 1709817096939 : ::1 &{req.mentod} : /favicon.ico
6 | 1709817121392 : ::1 &{req.mentod} : /api/users/
7 | 1709817193113 : ::1 &{req.mentod} : /users/
8 | 1709817199047 : ::1 &{req.mentod} : /users
9 | 1709817205834 : ::1 &{req.mentod} : /users/
10 | 1709817215414 : ::1 &{req.mentod} : /users/
11 | 1709817365659 : ::1 &{req.mentod} : /api/users
12 | 1709817404909 : ::1 &{req.mentod} : /api/users
13 | 1709817490776 : ::1 &{req.mentod} : /api/users/65e9be3c102400b6804a9502
14 | 1709817570154 : ::1 &{req.mentod} : /api/users/65e9be3c102400b6804a9502
15 |
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/middlewares/index.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 |
3 | function logReqRes(filename){
4 | return (req , res , next) =>{
5 | fs.appendFile(
6 | filename,
7 | `${Date.now()} : ${req.ip} &{req.mentod} : ${req.path}\n`,
8 | (err , data) =>{
9 | next();
10 | }
11 | );
12 | }
13 | }
14 |
15 | module.exports = {
16 | logReqRes,
17 | };
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/models/user.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | //Schema
4 | const userSchema = new mongoose.Schema({
5 | firstName: {
6 | type: String,
7 | required : true,
8 | },
9 | lastName : {
10 | type: String,
11 | },
12 | email:{
13 | type: String,
14 | required : true,
15 | unique: true,
16 | },
17 | jobTitle: {
18 | type: String,
19 | }
20 | },
21 | {timestamps: true}
22 | )
23 |
24 | const User = mongoose.model('user' , userSchema);
25 |
26 | module.exports = User;
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "13_building_rest_api_using_node_and_express",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3",
14 | "mongoose": "^8.2.1",
15 | "nodemon": "^3.1.0"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/20_Model_View_Controller_in_NodeJS/routes/user.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const {
3 | handleGetAllUsers ,
4 | handleGetUserById ,
5 | handleUpdateUserById,
6 | handleDeleteUserById,
7 | handleCreateNewUser,
8 | } = require('../controllers/user')
9 |
10 | const router = express.Router();
11 |
12 |
13 | //REST Api
14 |
15 | router
16 | .route('/')
17 | .get(handleGetAllUsers)
18 | .post(handleCreateNewUser);
19 |
20 |
21 | router.
22 | route('/:id')
23 | .get(handleGetUserById)
24 | .patch(handleUpdateUserById)
25 | .delete(handleDeleteUserById);
26 |
27 |
28 |
29 |
30 | module.exports = router;
--------------------------------------------------------------------------------
/21_Custom_URL_Shortener/connect.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | async function connectToMongoDB(url){
4 | return mongoose.connect(url);
5 | }
6 |
7 | module.exports= {
8 | connectToMongoDB
9 | }
--------------------------------------------------------------------------------
/21_Custom_URL_Shortener/controllers/url.js:
--------------------------------------------------------------------------------
1 | const {nanoid} = require("nanoid");
2 | const URL = require('../models/url')
3 | async function handleGenerateNewShortURL(req , res){
4 | const shortID = nanoid(8);
5 | const body = req.body;
6 | // console.log(shortID);
7 |
8 | if(!body.url) return res.status(400).json({error : 'url is required'});
9 |
10 | await URL.create({
11 | shortId : shortID,
12 | redirectURL : body.url,
13 | visitHistory : []
14 | });
15 |
16 | return res.json({id : shortID})
17 | }
18 |
19 | async function handleGetAnalytics(req , res){
20 | const shortId = req.params.shortId;
21 | const result = await URL.findOne({ shortId : shortId })
22 | return res.json({
23 | totalClicks: result.visitHistory.length,
24 | analytics: result.visitHistory,
25 | })
26 | }
27 |
28 | module.exports = {
29 | handleGenerateNewShortURL,
30 | handleGetAnalytics
31 | }
--------------------------------------------------------------------------------
/21_Custom_URL_Shortener/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const { connectToMongoDB } = require('./connect')
3 | const urlRoute = require('./routes/url')
4 | const URL = require('./models/url');
5 |
6 | const app = express();
7 | const PORT = 8001;
8 |
9 | connectToMongoDB('mongodb://127.0.0.1:27017/short-url')
10 | .then (()=> console.log("MongoDB connected"))
11 |
12 | app.use(express.json())
13 | app.use("/url" , urlRoute)
14 |
15 | app.get("/:shortId", async (req, res) => {
16 | const shortId = req.params.shortId;
17 | const entry = await URL.findOneAndUpdate(
18 | {
19 | shortId : shortId,
20 | },
21 | {
22 | $push: {
23 | visitHistory: {
24 | timestamp: Date.now(),
25 | },
26 | },
27 | }
28 | );
29 | res.redirect(entry.redirectURL);
30 | });
31 |
32 | app.listen(PORT , ()=> console.log(`Server started at port : ${PORT}`))
--------------------------------------------------------------------------------
/21_Custom_URL_Shortener/models/url.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const urlSchema = new mongoose.Schema(
4 | {
5 | shortId : {
6 | type : String,
7 | required : true,
8 | unique: true,
9 | },
10 | redirectURL :{
11 | type : String,
12 | required : true,
13 | },
14 | visitHistory: [
15 | { timestamp : {
16 | type : Number
17 | }}
18 | ]
19 | } ,
20 | { timestamp : true }
21 | );
22 |
23 |
24 | const URL = mongoose.model("url" , urlSchema)
25 |
26 | module.exports = URL;
--------------------------------------------------------------------------------
/21_Custom_URL_Shortener/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "21_custom_url_shortener",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "express": "^4.18.3",
14 | "mongoose": "^8.2.1",
15 | "nanoid": "^3.3.7",
16 | "nodemon": "^3.1.0"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/21_Custom_URL_Shortener/routes/url.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const {handleGenerateNewShortURL , handleGetAnalytics} = require("../controllers/url")
3 | const router = express.Router();
4 |
5 | router.post('/' , handleGenerateNewShortURL)
6 | router.get('/analytics/:shortId',handleGetAnalytics )
7 |
8 | module.exports = router;
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/Readme.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/22_Server_Side_Rendering_with_EJS_and_NodeJS/Readme.md
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/connect.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | async function connectToMongoDB(url){
4 | return mongoose.connect(url);
5 | }
6 |
7 | module.exports= {
8 | connectToMongoDB
9 | }
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/controllers/url.js:
--------------------------------------------------------------------------------
1 | const {nanoid} = require("nanoid");
2 | const URL = require('../models/url')
3 | async function handleGenerateNewShortURL(req , res){
4 | const shortID = nanoid(8);
5 | const body = req.body;
6 | // console.log(shortID);
7 |
8 | if(!body.url) return res.status(400).json({error : 'url is required'});
9 |
10 | await URL.create({
11 | shortId : shortID,
12 | redirectURL : body.url,
13 | visitHistory : [],
14 |
15 | });
16 |
17 | return res.render('home',{id : shortID})
18 | return res.json({id : shortID})
19 | }
20 |
21 | async function handleGetAnalytics(req , res){
22 | const shortId = req.params.shortId;
23 | const result = await URL.findOne({ shortId : shortId })
24 | return res.json({
25 | totalClicks: result.visitHistory.length,
26 | analytics: result.visitHistory,
27 | })
28 | }
29 |
30 | module.exports = {
31 | handleGenerateNewShortURL,
32 | handleGetAnalytics
33 | }
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const { connectToMongoDB } = require('./connect')
3 | const urlRoute = require('./routes/url')
4 | const staticRoute = require('./routes/staticRoute')
5 | const path = require('path')
6 | const URL = require('./models/url');
7 |
8 | const app = express();
9 | const PORT = 8001;
10 |
11 | connectToMongoDB('mongodb://127.0.0.1:27017/short-url')
12 | .then (()=> console.log("MongoDB connected"))
13 |
14 | app.set("view engine" , "ejs")
15 | app.set("views" , path.resolve("./views"))
16 |
17 | app.use(express.json())
18 | app.use(express.urlencoded({extended:false})) //for form data
19 |
20 | app.use("/url" , urlRoute)
21 | app.use("/" , staticRoute)
22 |
23 | // Server Side Rendering ->
24 | // Write html on server side -> complicated
25 | // For ease we use EJS
26 | app.get('/test' , async(req , res)=>{
27 | const allUrls = await URL.find({});
28 | // return res.end(`
29 | //
30 | //
31 | //
32 | //
33 | // ${allUrls.map( url => `
34 | // ${url.shortId} -
35 | // ${url.redirectURL} -
36 | // ${url.visitHistory.length} `
37 | // ).join("")
38 | // }
39 | //
40 | //
41 | // `
42 |
43 | // )
44 |
45 | return res.render('home',{
46 | urls: allUrls,
47 | })
48 | })
49 |
50 |
51 |
52 | app.get("/url/:shortId", async (req, res) => {
53 | const shortId = req.params.shortId;
54 | const entry = await URL.findOneAndUpdate(
55 | {
56 | shortId : shortId,
57 | },
58 | {
59 | $push: {
60 | visitHistory: {
61 | timestamp: Date.now(),
62 | },
63 | },
64 | }
65 | );
66 | res.redirect(entry.redirectURL);
67 | });
68 |
69 | app.listen(PORT , ()=> console.log(`Server started at port : ${PORT}`))
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/models/url.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const urlSchema = new mongoose.Schema(
4 | {
5 | shortId : {
6 | type : String,
7 | required : true,
8 | unique: true,
9 | },
10 | redirectURL :{
11 | type : String,
12 | required : true,
13 | },
14 | visitHistory: [
15 | { timestamp : {
16 | type : Number
17 | }}
18 | ],
19 | createdBy :{
20 | type: mongoose.Schema.Types.ObjectId,
21 | ref: "users",
22 | }
23 | } ,
24 | { timestamp : true }
25 | );
26 |
27 |
28 | const URL = mongoose.model("url" , urlSchema)
29 |
30 | module.exports = URL;
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "21_custom_url_shortener",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "ejs": "^3.1.9",
14 | "express": "^4.18.3",
15 | "mongoose": "^8.2.1",
16 | "nanoid": "^3.3.7",
17 | "nodemon": "^3.1.0"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/routes/staticRoute.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 |
3 | const router = express.Router();
4 |
5 | router.get('/' , async(req, res)=>{
6 | const allUrls = await URL.find({})
7 | return res.render("home",{
8 | urls: allUrls,
9 | })
10 | })
11 |
12 | module.exports = router;
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/routes/url.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const {handleGenerateNewShortURL , handleGetAnalytics} = require("../controllers/url")
3 | const router = express.Router();
4 |
5 | router.post('/' , handleGenerateNewShortURL)
6 | router.get('/analytics/:shortId',handleGetAnalytics )
7 |
8 | module.exports = router;
--------------------------------------------------------------------------------
/22_Server_Side_Rendering_with_EJS_and_NodeJS/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Home
7 |
12 |
13 |
14 | URL Shortner
15 | <% if(locals.id){
16 | %>
17 | URL Generated : http://localhost:8001/url/<%= id%>
18 | <%
19 | } %>
20 |
21 |
26 |
27 |
28 |
29 | <% if(locals.urls){
30 | %>
31 |
32 |
33 | S. no
34 | ShortID
35 | Redirect
36 | Clicks
37 |
38 |
39 | <% urls.forEach((url , index )=> {
40 | %>
41 |
42 | <%= index +1 %>
43 | <%= url.shortId %>
44 | <%= url.redirectURL %>
45 | <%= url.visitHistory.length %>
46 |
47 | <%
48 | });
49 | %>
50 |
51 |
52 | <%
53 | } %>
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/Readme.md:
--------------------------------------------------------------------------------
1 | # Authentication
2 |
3 | ## Authentication Patterns
4 | 1. Statefull - Which maintains state or data on server side
5 |
6 | 2. Stateless - Which has no state.
7 |
8 | In statefull authentication server works as a parking boy which stores the car no. with a unique mapped no.
9 |
10 | Server gives the mapped number gives to the user as a parking ticket .
11 |
12 | When user visit again to take the car the parking boy (server) maps the data , the user is authentic or not . If yes then server gives the permission to user to take the car.(maintain a state)
13 |
14 |
15 | 
16 |
17 | ## How to transfer uid?
18 |
19 | Server can transfer the unique id using cookies, respose , headers to the cilent.
20 |
21 | ## Express Flow
22 |
23 | 
24 |
25 |
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/connect.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | async function connectToMongoDB(url){
4 | return mongoose.connect(url);
5 | }
6 |
7 | module.exports= {
8 | connectToMongoDB
9 | }
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/controllers/url.js:
--------------------------------------------------------------------------------
1 | const {nanoid} = require("nanoid");
2 | const URL = require('../models/url')
3 | async function handleGenerateNewShortURL(req , res){
4 | const shortID = nanoid(8);
5 | const body = req.body;
6 | // console.log(shortID);
7 |
8 | if(!body.url) return res.status(400).json({error : 'url is required'});
9 |
10 | await URL.create({
11 | shortId : shortID,
12 | redirectURL : body.url,
13 | visitHistory : [],
14 | createdBy: req.user._id,
15 | });
16 |
17 | return res.render('home',{id : shortID})
18 | return res.json({id : shortID})
19 | }
20 |
21 | async function handleGetAnalytics(req , res){
22 | const shortId = req.params.shortId;
23 | const result = await URL.findOne({ shortId : shortId })
24 | return res.json({
25 | totalClicks: result.visitHistory.length,
26 | analytics: result.visitHistory,
27 | })
28 | }
29 |
30 | module.exports = {
31 | handleGenerateNewShortURL,
32 | handleGetAnalytics
33 | }
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/controllers/user.js:
--------------------------------------------------------------------------------
1 | const User = require('../models/user')
2 | const {v4:uuidv4} = require('uuid')
3 | const { setUser } = require('../service/auth')
4 | async function handleUserSignup(req ,res){
5 | const {name , email , password} = req.body;
6 |
7 | await User.create({
8 | name,
9 | email,
10 | password,
11 | });
12 | return res.redirect("/");
13 | }
14 |
15 | async function handleUserLogin(req ,res){
16 | const { email , password} = req.body;
17 |
18 | const user = await User.findOne({email , password});
19 | if(!user) return res.render("login" , {
20 | error:"Invalid Username or Password",
21 | });
22 |
23 | const sessionId = uuidv4();
24 | setUser(sessionId , user);
25 | res.cookie("uid" , sessionId);
26 | return res.redirect("/");
27 |
28 | }
29 |
30 | module.exports = {
31 | handleUserSignup,
32 | handleUserLogin
33 |
34 | };
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/images/expressflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/23_Building_Node.js_Authentication_from_Scratch/images/expressflow.png
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/images/stateful.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/23_Building_Node.js_Authentication_from_Scratch/images/stateful.png
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/middlewares/auth.js:
--------------------------------------------------------------------------------
1 | const {getUser} = require('../service/auth')
2 | async function restrictToLoggedinUserOnly(req , res , next){
3 | const userUid = req.cookies?.uid;
4 |
5 | if(!userUid) return res.redirect("/login");
6 | const user = getUser(userUid);
7 |
8 | if(!user) return res.redirect("/login");
9 |
10 | req.user = user;
11 | next();
12 | }
13 |
14 | async function checkAuth(req , res , next){
15 | const userUid = req.cookies?.uid;
16 | const user = getUser(userUid);
17 | req.user = user;
18 | next();
19 | }
20 |
21 | module.exports= {
22 | restrictToLoggedinUserOnly,
23 | checkAuth
24 | };
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/models/url.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const urlSchema = new mongoose.Schema(
4 | {
5 | shortId : {
6 | type : String,
7 | required : true,
8 | unique: true,
9 | },
10 | redirectURL :{
11 | type : String,
12 | required : true,
13 | },
14 | visitHistory: [
15 | { timestamp : {
16 | type : Number
17 | }}
18 | ],
19 | createdBy : {
20 | type: mongoose.Schema.Types.ObjectId,
21 | ref: 'users'
22 | }
23 | } ,
24 | { timestamp : true }
25 | );
26 |
27 |
28 | const URL = mongoose.model("url" , urlSchema)
29 |
30 | module.exports = URL;
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/models/user.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const userSchema = new mongoose.Schema({
4 | name:{
5 | type: String,
6 | required : true,
7 | },
8 | email:{
9 | type:String,
10 | required: true,
11 | unquie : true,
12 | },
13 | password:{
14 | type: String,
15 | required: true,
16 | },
17 |
18 |
19 |
20 | },{timestamps:true});
21 |
22 | const User = mongoose.model('user', userSchema);
23 |
24 | module.exports = User;
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "21_custom_url_shortener",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cookie-parser": "^1.4.6",
14 | "ejs": "^3.1.9",
15 | "express": "^4.18.3",
16 | "mongoose": "^8.2.1",
17 | "nanoid": "^3.3.7",
18 | "nodemon": "^3.1.0",
19 | "uuid": "^9.0.1"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/routes/staticRoute.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const URL = require('../models/url');
3 | const router = express.Router();
4 |
5 |
6 | router.get('/' , async(req, res)=>{
7 | if(!req.user) return res.redirect('/login')
8 | const allUrls = await URL.find({ createdBy : req.user._id});
9 | return res.render("home",{
10 | urls: allUrls,
11 | })
12 | })
13 |
14 |
15 | router.get('/signup', async(req , res)=>{
16 | return res.render("signup");
17 | })
18 |
19 | router.get('/login', async(req , res)=>{
20 | return res.render("login");
21 | })
22 |
23 |
24 |
25 | module.exports = router;
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/routes/url.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const {handleGenerateNewShortURL , handleGetAnalytics} = require("../controllers/url")
3 | const router = express.Router();
4 |
5 | router.post('/' , handleGenerateNewShortURL)
6 | router.get('/analytics/:shortId',handleGetAnalytics )
7 |
8 | module.exports = router;
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/routes/user.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const {handleUserLogin , handleUserSignup} = require("../controllers/user");
3 |
4 | const router = express.Router();
5 |
6 |
7 | router.post('/', handleUserSignup)
8 | router.post('/login',handleUserLogin)
9 |
10 | module.exports = router;
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/service/auth.js:
--------------------------------------------------------------------------------
1 | const sessionIdToUserMap = new Map();
2 |
3 | function setUser(id , user){
4 | sessionIdToUserMap.set(id , user);
5 | }
6 |
7 | function getUser(id){
8 | return sessionIdToUserMap.get(id);
9 | }
10 |
11 | module.exports={
12 | setUser,
13 | getUser
14 | };
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Home
7 |
12 |
13 |
14 | URL Shortner
15 | <% if(locals.id){
16 | %>
17 | URL Generated : http://localhost:8001/url/<%= id%>
18 | <%
19 | } %>
20 |
21 |
26 |
27 |
28 |
29 | <% if(locals.urls){
30 | %>
31 |
32 |
33 | S. no
34 | ShortID
35 | Redirect
36 | Clicks
37 |
38 |
39 | <% urls.forEach((url , index )=> {
40 | %>
41 |
42 | <%= index +1 %>
43 | <%= url.shortId %>
44 | <%= url.redirectURL %>
45 | <%= url.visitHistory.length %>
46 |
47 | <%
48 | });
49 | %>
50 |
51 |
52 | <%
53 | } %>
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/views/login.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Login
7 |
12 |
13 |
14 | Login
15 |
25 |
26 |
--------------------------------------------------------------------------------
/23_Building_Node.js_Authentication_from_Scratch/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Sign Up
7 |
12 |
13 |
14 | Sign Up
15 |
27 |
28 |
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/Readme.md:
--------------------------------------------------------------------------------
1 | ## Problems in Statefull Authentication
2 |
3 | => If server restart or some reason server lost , all users get logged out.
4 |
5 | => Memory intensive
6 |
7 | ## Stateless Authentication
8 |
9 | => No states
10 | => We use JWT(JSON Web Tokens) Tokens
11 | => Maintain the state on local browser using encoded msg of payload(token) and secret key.
12 | => Secret should be secret.
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/connect.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | async function connectToMongoDB(url){
4 | return mongoose.connect(url);
5 | }
6 |
7 | module.exports= {
8 | connectToMongoDB
9 | }
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/controllers/url.js:
--------------------------------------------------------------------------------
1 | const {nanoid} = require("nanoid");
2 | const URL = require('../models/url')
3 | async function handleGenerateNewShortURL(req , res){
4 | const shortID = nanoid(8);
5 | const body = req.body;
6 | // console.log(shortID);
7 |
8 | if(!body.url) return res.status(400).json({error : 'url is required'});
9 |
10 | await URL.create({
11 | shortId : shortID,
12 | redirectURL : body.url,
13 | visitHistory : [],
14 | createdBy: req.user._id,
15 | });
16 |
17 | return res.render('home',{id : shortID})
18 | return res.json({id : shortID})
19 | }
20 |
21 | async function handleGetAnalytics(req , res){
22 | const shortId = req.params.shortId;
23 | const result = await URL.findOne({ shortId : shortId })
24 | return res.json({
25 | totalClicks: result.visitHistory.length,
26 | analytics: result.visitHistory,
27 | })
28 | }
29 |
30 | module.exports = {
31 | handleGenerateNewShortURL,
32 | handleGetAnalytics
33 | }
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/controllers/user.js:
--------------------------------------------------------------------------------
1 | const User = require('../models/user')
2 | const {v4:uuidv4} = require('uuid')
3 | const { setUser } = require('../service/auth')
4 | async function handleUserSignup(req ,res){
5 | const {name , email , password} = req.body;
6 |
7 | await User.create({
8 | name,
9 | email,
10 | password,
11 | });
12 | return res.redirect("/");
13 | }
14 |
15 | async function handleUserLogin(req ,res){
16 | const { email , password} = req.body;
17 |
18 | const user = await User.findOne({email , password});
19 | if(!user) return res.render("login" , {
20 | error:"Invalid Username or Password",
21 | });
22 |
23 |
24 | const token = setUser(user);
25 | res.cookie("uid" , token);
26 | return res.redirect("/");
27 |
28 | }
29 |
30 | module.exports = {
31 | handleUserSignup,
32 | handleUserLogin
33 |
34 | };
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/images/expressflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/24_JWT_Authentication_in_NodeJS/images/expressflow.png
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/images/stateful.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/24_JWT_Authentication_in_NodeJS/images/stateful.png
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const { connectToMongoDB } = require('./connect')
3 | const path = require('path')
4 | const URL = require('./models/url');
5 | const cookieParser = require('cookie-parser')
6 | const {restrictToLoggedinUserOnly , checkAuth} = require('./middlewares/auth')
7 |
8 | const urlRoute = require('./routes/url')
9 | const staticRoute = require('./routes/staticRoute')
10 | const userRoute = require('./routes/user')
11 |
12 | const app = express();
13 | const PORT = 8001;
14 |
15 | connectToMongoDB('mongodb://127.0.0.1:27017/short-url')
16 | .then (()=> console.log("MongoDB connected"))
17 |
18 | app.set("view engine" , "ejs")
19 | app.set("views" , path.resolve("./views"))
20 |
21 | app.use(express.json())
22 | app.use(express.urlencoded({extended:false})) //for form data
23 | app.use(cookieParser())
24 |
25 | app.use("/url" , restrictToLoggedinUserOnly , urlRoute)
26 | app.use("/" , checkAuth , staticRoute)
27 | app.use("/user", userRoute)
28 |
29 | // Server Side Rendering ->
30 | // Write html on server side -> complicated
31 | // For ease we use EJS
32 | app.get('/test' , async(req , res)=>{
33 | const allUrls = await URL.find({});
34 | // return res.end(`
35 | //
36 | //
37 | //
38 | //
39 | // ${allUrls.map( url => `
40 | // ${url.shortId} -
41 | // ${url.redirectURL} -
42 | // ${url.visitHistory.length} `
43 | // ).join("")
44 | // }
45 | //
46 | //
47 | // `
48 |
49 | // )
50 |
51 | return res.render('home',{
52 | urls: allUrls,
53 | })
54 | })
55 |
56 |
57 |
58 | app.get("/url/:shortId", async (req, res) => {
59 | const shortId = req.params.shortId;
60 | const entry = await URL.findOneAndUpdate(
61 | {
62 | shortId : shortId,
63 | },
64 | {
65 | $push: {
66 | visitHistory: {
67 | timestamp: Date.now(),
68 | },
69 | },
70 | }
71 | );
72 | res.redirect(entry.redirectURL);
73 | });
74 |
75 | app.listen(PORT , ()=> console.log(`Server started at port : ${PORT}`))
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/middlewares/auth.js:
--------------------------------------------------------------------------------
1 | const {getUser} = require('../service/auth')
2 | async function restrictToLoggedinUserOnly(req , res , next){
3 | const userUid = req.cookies?.uid;
4 |
5 | if(!userUid) return res.redirect("/login");
6 | const user = getUser(userUid);
7 |
8 | if(!user) return res.redirect("/login");
9 |
10 | req.user = user;
11 | next();
12 | }
13 |
14 | async function checkAuth(req , res , next){
15 | const userUid = req.cookies?.uid;
16 | const user = getUser(userUid);
17 | req.user = user;
18 | next();
19 | }
20 |
21 | module.exports= {
22 | restrictToLoggedinUserOnly,
23 | checkAuth
24 | };
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/models/url.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const urlSchema = new mongoose.Schema(
4 | {
5 | shortId : {
6 | type : String,
7 | required : true,
8 | unique: true,
9 | },
10 | redirectURL :{
11 | type : String,
12 | required : true,
13 | },
14 | visitHistory: [
15 | { timestamp : {
16 | type : Number
17 | }}
18 | ],
19 | createdBy : {
20 | type: mongoose.Schema.Types.ObjectId,
21 | ref: 'users'
22 | }
23 | } ,
24 | { timestamp : true }
25 | );
26 |
27 |
28 | const URL = mongoose.model("url" , urlSchema)
29 |
30 | module.exports = URL;
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/models/user.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const userSchema = new mongoose.Schema({
4 | name:{
5 | type: String,
6 | required : true,
7 | },
8 | email:{
9 | type:String,
10 | required: true,
11 | unquie : true,
12 | },
13 | password:{
14 | type: String,
15 | required: true,
16 | },
17 |
18 |
19 |
20 | },{timestamps:true});
21 |
22 | const User = mongoose.model('user', userSchema);
23 |
24 | module.exports = User;
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "21_custom_url_shortener",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cookie-parser": "^1.4.6",
14 | "ejs": "^3.1.9",
15 | "express": "^4.18.3",
16 | "jsonwebtoken": "^9.0.2",
17 | "mongoose": "^8.2.1",
18 | "nanoid": "^3.3.7",
19 | "nodemon": "^3.1.0",
20 | "uuid": "^9.0.1"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/routes/staticRoute.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const URL = require('../models/url');
3 | const router = express.Router();
4 |
5 |
6 | router.get('/' , async(req, res)=>{
7 | if(!req.user) return res.redirect('/login')
8 | const allUrls = await URL.find({ createdBy : req.user._id});
9 | return res.render("home",{
10 | urls: allUrls,
11 | })
12 | })
13 |
14 |
15 | router.get('/signup', async(req , res)=>{
16 | return res.render("signup");
17 | })
18 |
19 | router.get('/login', async(req , res)=>{
20 | return res.render("login");
21 | })
22 |
23 |
24 |
25 | module.exports = router;
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/routes/url.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const {handleGenerateNewShortURL , handleGetAnalytics} = require("../controllers/url")
3 | const router = express.Router();
4 |
5 | router.post('/' , handleGenerateNewShortURL)
6 | router.get('/analytics/:shortId',handleGetAnalytics )
7 |
8 | module.exports = router;
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/routes/user.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const {handleUserLogin , handleUserSignup} = require("../controllers/user");
3 |
4 | const router = express.Router();
5 |
6 |
7 | router.post('/', handleUserSignup)
8 | router.post('/login',handleUserLogin)
9 |
10 | module.exports = router;
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/service/auth.js:
--------------------------------------------------------------------------------
1 | //Removing state and importing JWT
2 |
3 | const jwt = require("jsonwebtoken");
4 | const secret = "Ayush$123@$"
5 |
6 | function setUser( user){
7 | return jwt.sign({
8 | _id: user._id,
9 | email: user.email,
10 | }, secret);
11 | //assigning user object as a payload
12 | }
13 |
14 | function getUser(token){
15 | try {
16 | return jwt.verify(token, secret);
17 | } catch (error) {
18 | return null;
19 | }
20 |
21 | }
22 |
23 | module.exports={
24 | setUser,
25 | getUser
26 | };
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Home
7 |
12 |
13 |
14 | URL Shortner
15 | <% if(locals.id){
16 | %>
17 | URL Generated : http://localhost:8001/url/<%= id%>
18 | <%
19 | } %>
20 |
21 |
26 |
27 |
28 |
29 | <% if(locals.urls){
30 | %>
31 |
32 |
33 | S. no
34 | ShortID
35 | Redirect
36 | Clicks
37 |
38 |
39 | <% urls.forEach((url , index )=> {
40 | %>
41 |
42 | <%= index +1 %>
43 | <%= url.shortId %>
44 | <%= url.redirectURL %>
45 | <%= url.visitHistory.length %>
46 |
47 | <%
48 | });
49 | %>
50 |
51 |
52 | <%
53 | } %>
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/views/login.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Login
7 |
12 |
13 |
14 | Login
15 |
25 |
26 |
--------------------------------------------------------------------------------
/24_JWT_Authentication_in_NodeJS/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Sign Up
7 |
12 |
13 |
14 | Sign Up
15 |
27 |
28 |
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/Readme.md:
--------------------------------------------------------------------------------
1 | # Cookies in NodeJS
2 |
3 | Server make the token.
4 |
5 | Server can the send the token to the user through `Cookies` and `Response`.
6 |
7 | ## Using Browser - auto
8 | Browser stores the cookies.
9 |
10 | We can use the cookie to validate the user.
11 |
12 | The server makes the cookies for the domain to which those cookies belong.(Cookies are domain specific.)
13 |
14 | We can specify domain to the cookie.Which domain can acess that cookie.
15 |
16 | We can also specify the expiration of the cookie.
17 |
18 | ```javascript
19 | res.cookie("uid", token , {
20 | domain : "ayushk.dev" // ayushk.dev can access
21 |
22 | domain : ".ayushk.dev" // blog.ayushk.dev can access
23 | //app.ayushk.dev also can access
24 |
25 | })
26 | ```
27 |
28 | It is only limited to the browser.
29 |
30 | ## Using Header - json
31 |
32 | Bearer authentication is also called as token authentication.
33 | It is an `HTTP auth`.
34 |
35 | ```javascript
36 | Header{
37 | Authorization : Bearer
38 | }
39 |
40 | ```
41 |
42 | Server reads the header and removes the bearer and takes the token to validate the user.
43 |
44 |
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/connect.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | async function connectToMongoDB(url){
4 | return mongoose.connect(url);
5 | }
6 |
7 | module.exports= {
8 | connectToMongoDB
9 | }
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/controllers/url.js:
--------------------------------------------------------------------------------
1 | const {nanoid} = require("nanoid");
2 | const URL = require('../models/url')
3 | async function handleGenerateNewShortURL(req , res){
4 | const shortID = nanoid(8);
5 | const body = req.body;
6 | // console.log(shortID);
7 |
8 | if(!body.url) return res.status(400).json({error : 'url is required'});
9 |
10 | await URL.create({
11 | shortId : shortID,
12 | redirectURL : body.url,
13 | visitHistory : [],
14 | createdBy: req.user._id,
15 | });
16 |
17 | return res.render('home',{id : shortID})
18 | return res.json({id : shortID})
19 | }
20 |
21 | async function handleGetAnalytics(req , res){
22 | const shortId = req.params.shortId;
23 | const result = await URL.findOne({ shortId : shortId })
24 | return res.json({
25 | totalClicks: result.visitHistory.length,
26 | analytics: result.visitHistory,
27 | })
28 | }
29 |
30 | module.exports = {
31 | handleGenerateNewShortURL,
32 | handleGetAnalytics
33 | }
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/controllers/user.js:
--------------------------------------------------------------------------------
1 | const User = require('../models/user')
2 | const {v4:uuidv4} = require('uuid')
3 | const { setUser } = require('../service/auth')
4 | async function handleUserSignup(req ,res){
5 | const {name , email , password} = req.body;
6 |
7 | await User.create({
8 | name,
9 | email,
10 | password,
11 | });
12 | return res.redirect("/");
13 | }
14 |
15 | async function handleUserLogin(req ,res){
16 | const { email , password} = req.body;
17 |
18 | const user = await User.findOne({email , password});
19 | if(!user) return res.render("login" , {
20 | error:"Invalid Username or Password",
21 | });
22 |
23 |
24 | const token = setUser(user);
25 | console.log(req.body)
26 | // res.cookie("uid" , token);
27 | // return res.redirect("/");
28 | return res.json({ token });
29 |
30 | }
31 |
32 | module.exports = {
33 | handleUserSignup,
34 | handleUserLogin
35 |
36 | };
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const { connectToMongoDB } = require('./connect')
3 | const path = require('path')
4 | const URL = require('./models/url');
5 | const cookieParser = require('cookie-parser')
6 | const {restrictToLoggedinUserOnly , checkAuth} = require('./middlewares/auth')
7 |
8 | const urlRoute = require('./routes/url')
9 | const staticRoute = require('./routes/staticRoute')
10 | const userRoute = require('./routes/user')
11 |
12 | const app = express();
13 | const PORT = 8001;
14 |
15 | connectToMongoDB('mongodb://127.0.0.1:27017/short-url')
16 | .then (()=> console.log("MongoDB connected"))
17 |
18 | app.set("view engine" , "ejs")
19 | app.set("views" , path.resolve("./views"))
20 |
21 | app.use(express.json())
22 | app.use(express.urlencoded({extended:false})) //for form data
23 | app.use(cookieParser())
24 |
25 | app.use("/url" , restrictToLoggedinUserOnly , urlRoute)
26 | app.use("/" , checkAuth , staticRoute)
27 | app.use("/user", userRoute)
28 |
29 | // Server Side Rendering ->
30 | // Write html on server side -> complicated
31 | // For ease we use EJS
32 | app.get('/test' , async(req , res)=>{
33 | const allUrls = await URL.find({});
34 | // return res.end(`
35 | //
36 | //
37 | //
38 | //
39 | // ${allUrls.map( url => `
40 | // ${url.shortId} -
41 | // ${url.redirectURL} -
42 | // ${url.visitHistory.length} `
43 | // ).join("")
44 | // }
45 | //
46 | //
47 | // `
48 |
49 | // )
50 |
51 | return res.render('home',{
52 | urls: allUrls,
53 | })
54 | })
55 |
56 |
57 |
58 | app.get("/url/:shortId", async (req, res) => {
59 | const shortId = req.params.shortId;
60 | const entry = await URL.findOneAndUpdate(
61 | {
62 | shortId : shortId,
63 | },
64 | {
65 | $push: {
66 | visitHistory: {
67 | timestamp: Date.now(),
68 | },
69 | },
70 | }
71 | );
72 | res.redirect(entry.redirectURL);
73 | });
74 |
75 | app.listen(PORT , ()=> console.log(`Server started at port : ${PORT}`))
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/middlewares/auth.js:
--------------------------------------------------------------------------------
1 | const {getUser} = require('../service/auth')
2 | async function restrictToLoggedinUserOnly(req , res , next){
3 | // const userUid = req.cookies?.uid;
4 | const userUid = req.headers["authorization"];
5 | if(!userUid) return res.redirect("/login");
6 | const token = userUid.split("Bearer ")[1];
7 | // Bearer jkd2132jk3123
8 | const user = getUser(token);
9 |
10 |
11 | if(!userUid) return res.redirect("/login");
12 | // const user = getUser(userUid);
13 |
14 | if(!user) return res.redirect("/login");
15 |
16 | req.user = user;
17 | next();
18 | }
19 |
20 | async function checkAuth(req , res , next){
21 | // const userUid = req.cookies?.uid;
22 | const userUid = req.headers["authorization"];
23 | const token = userUid.split("Bearer ")[1];
24 | console.log(req.headers);
25 | const user = getUser(token);
26 |
27 | // const user = getUser(userUid);
28 | req.user = user;
29 | next();
30 | }
31 |
32 | module.exports= {
33 | restrictToLoggedinUserOnly,
34 | checkAuth
35 | };
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/models/url.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const urlSchema = new mongoose.Schema(
4 | {
5 | shortId : {
6 | type : String,
7 | required : true,
8 | unique: true,
9 | },
10 | redirectURL :{
11 | type : String,
12 | required : true,
13 | },
14 | visitHistory: [
15 | { timestamp : {
16 | type : Number
17 | }}
18 | ],
19 | createdBy : {
20 | type: mongoose.Schema.Types.ObjectId,
21 | ref: 'users'
22 | }
23 | } ,
24 | { timestamp : true }
25 | );
26 |
27 |
28 | const URL = mongoose.model("url" , urlSchema)
29 |
30 | module.exports = URL;
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/models/user.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const userSchema = new mongoose.Schema({
4 | name:{
5 | type: String,
6 | required : true,
7 | },
8 | email:{
9 | type:String,
10 | required: true,
11 | unquie : true,
12 | },
13 | password:{
14 | type: String,
15 | required: true,
16 | },
17 |
18 |
19 |
20 | },{timestamps:true});
21 |
22 | const User = mongoose.model('user', userSchema);
23 |
24 | module.exports = User;
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "21_custom_url_shortener",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cookie-parser": "^1.4.6",
14 | "ejs": "^3.1.9",
15 | "express": "^4.18.3",
16 | "jsonwebtoken": "^9.0.2",
17 | "mongoose": "^8.2.1",
18 | "nanoid": "^3.3.7",
19 | "nodemon": "^3.1.0",
20 | "uuid": "^9.0.1"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/routes/staticRoute.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const URL = require('../models/url');
3 | const router = express.Router();
4 |
5 |
6 | router.get('/' , async(req, res)=>{
7 | if(!req.user) return res.redirect('/login')
8 | const allUrls = await URL.find({ createdBy : req.user._id});
9 | return res.render("home",{
10 | urls: allUrls,
11 | })
12 | })
13 |
14 |
15 | router.get('/signup', async(req , res)=>{
16 | return res.render("signup");
17 | })
18 |
19 | router.get('/login', async(req , res)=>{
20 | return res.render("login");
21 | })
22 |
23 |
24 |
25 | module.exports = router;
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/routes/url.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const {handleGenerateNewShortURL , handleGetAnalytics} = require("../controllers/url")
3 | const router = express.Router();
4 |
5 | router.post('/' , handleGenerateNewShortURL)
6 | router.get('/analytics/:shortId',handleGetAnalytics )
7 |
8 | module.exports = router;
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/routes/user.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const {handleUserLogin , handleUserSignup} = require("../controllers/user");
3 |
4 | const router = express.Router();
5 |
6 |
7 | router.post('/', handleUserSignup)
8 | router.post('/login',handleUserLogin)
9 |
10 | module.exports = router;
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/service/auth.js:
--------------------------------------------------------------------------------
1 | //Removing state and importing JWT
2 |
3 | const jwt = require("jsonwebtoken");
4 | const secret = "Ayush$123@$"
5 |
6 | function setUser( user){
7 | return jwt.sign({
8 | _id: user._id,
9 | email: user.email,
10 | }, secret);
11 | //assigning user object as a payload
12 | }
13 |
14 | function getUser(token){
15 | try {
16 | return jwt.verify(token, secret);
17 | } catch (error) {
18 | return null;
19 | }
20 |
21 | }
22 |
23 | module.exports={
24 | setUser,
25 | getUser
26 | };
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Home
7 |
12 |
13 |
14 | URL Shortner
15 | <% if(locals.id){
16 | %>
17 | URL Generated : http://localhost:8001/url/<%= id%>
18 | <%
19 | } %>
20 |
21 |
26 |
27 |
28 |
29 | <% if(locals.urls){
30 | %>
31 |
32 |
33 | S. no
34 | ShortID
35 | Redirect
36 | Clicks
37 |
38 |
39 | <% urls.forEach((url , index )=> {
40 | %>
41 |
42 | <%= index +1 %>
43 | <%= url.shortId %>
44 | <%= url.redirectURL %>
45 | <%= url.visitHistory.length %>
46 |
47 | <%
48 | });
49 | %>
50 |
51 |
52 | <%
53 | } %>
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/views/login.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Login
7 |
12 |
13 |
14 | Login
15 |
25 |
26 |
--------------------------------------------------------------------------------
/25_What_are_Cookies_in_NodeJS/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Sign Up
7 |
12 |
13 |
14 | Sign Up
15 |
27 |
28 |
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/Readme.md:
--------------------------------------------------------------------------------
1 | # Authorization
2 |
3 | Authorization is the process of giving someone the ability to access a resource.
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/connect.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose');
2 |
3 | async function connectToMongoDB(url){
4 | return mongoose.connect(url);
5 | }
6 |
7 | module.exports= {
8 | connectToMongoDB
9 | }
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/controllers/url.js:
--------------------------------------------------------------------------------
1 | const {nanoid} = require("nanoid");
2 | const URL = require('../models/url')
3 | async function handleGenerateNewShortURL(req , res){
4 | const shortID = nanoid(8);
5 | const body = req.body;
6 | // console.log(shortID);
7 |
8 | if(!body.url) return res.status(400).json({error : 'url is required'});
9 |
10 | await URL.create({
11 | shortId : shortID,
12 | redirectURL : body.url,
13 | visitHistory : [],
14 | createdBy: req.user._id,
15 | });
16 |
17 | return res.render('home',{id : shortID})
18 | return res.json({id : shortID})
19 | }
20 |
21 | async function handleGetAnalytics(req , res){
22 | const shortId = req.params.shortId;
23 | const result = await URL.findOne({ shortId : shortId })
24 | return res.json({
25 | totalClicks: result.visitHistory.length,
26 | analytics: result.visitHistory,
27 | })
28 | }
29 |
30 | module.exports = {
31 | handleGenerateNewShortURL,
32 | handleGetAnalytics
33 | }
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/controllers/user.js:
--------------------------------------------------------------------------------
1 | const User = require('../models/user')
2 | const {v4:uuidv4} = require('uuid')
3 | const { setUser } = require('../service/auth')
4 | async function handleUserSignup(req ,res){
5 | const {name , email , password} = req.body;
6 |
7 | await User.create({
8 | name,
9 | email,
10 | password,
11 | });
12 | return res.redirect("/");
13 | }
14 |
15 | async function handleUserLogin(req ,res){
16 | const { email , password} = req.body;
17 |
18 | const user = await User.findOne({email , password});
19 | if(!user) return res.render("login" , {
20 | error:"Invalid Username or Password",
21 | });
22 |
23 |
24 | const token = setUser(user);
25 | res.cookie("token",token);
26 | return res.redirect("/");s
27 |
28 | }
29 |
30 | module.exports = {
31 | handleUserSignup,
32 | handleUserLogin
33 |
34 | };
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const { connectToMongoDB } = require('./connect')
3 | const path = require('path')
4 | const URL = require('./models/url');
5 | const cookieParser = require('cookie-parser')
6 | const { checkForAuthentication , restrictTo} = require('./middlewares/auth')
7 |
8 | const urlRoute = require('./routes/url')
9 | const staticRoute = require('./routes/staticRoute')
10 | const userRoute = require('./routes/user')
11 |
12 | const app = express();
13 | const PORT = 8001;
14 |
15 | connectToMongoDB('mongodb://127.0.0.1:27017/short-url')
16 | .then (()=> console.log("MongoDB connected"))
17 |
18 | app.set("view engine" , "ejs")
19 | app.set("views" , path.resolve("./views"))
20 |
21 | app.use(express.json())
22 | app.use(express.urlencoded({extended:false})) //for form data
23 | app.use(cookieParser())
24 | app.use(checkForAuthentication)
25 |
26 | app.use("/url" ,restrictTo(["NORMAL"]) , urlRoute)
27 | app.use("/" , staticRoute)
28 | app.use("/user", userRoute)
29 |
30 | // Server Side Rendering ->
31 | // Write html on server side -> complicated
32 | // For ease we use EJS
33 | app.get('/test' , async(req , res)=>{
34 | const allUrls = await URL.find({});
35 | // return res.end(`
36 | //
37 | //
38 | //
39 | //
40 | // ${allUrls.map( url => `
41 | // ${url.shortId} -
42 | // ${url.redirectURL} -
43 | // ${url.visitHistory.length} `
44 | // ).join("")
45 | // }
46 | //
47 | //
48 | // `
49 |
50 | // )
51 |
52 | return res.render('home',{
53 | urls: allUrls,
54 | })
55 | })
56 |
57 |
58 |
59 | app.get("/url/:shortId", async (req, res) => {
60 | const shortId = req.params.shortId;
61 | const entry = await URL.findOneAndUpdate(
62 | {
63 | shortId : shortId,
64 | },
65 | {
66 | $push: {
67 | visitHistory: {
68 | timestamp: Date.now(),
69 | },
70 | },
71 | }
72 | );
73 | res.redirect(entry.redirectURL);
74 | });
75 |
76 | app.listen(PORT , ()=> console.log(`Server started at port : ${PORT}`))
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/middlewares/auth.js:
--------------------------------------------------------------------------------
1 | const {getUser} = require('../service/auth')
2 |
3 | function checkForAuthentication(req, res, next){
4 | const tokenCookie = req.cookies?.token;
5 | req.user = null;
6 | if(!tokenCookie) return next();
7 |
8 | const token = tokenCookie;
9 | const user = getUser(token);
10 | req.user=user;
11 | return next()
12 | }
13 |
14 | // ADMIN , Normal
15 | function restrictTo(roles = []){
16 | return function(req, res, next){
17 | if(!req.user ) return res.redirect("/login");
18 | if(!roles.includes(req.user.role)) return res.end("UnAuthorized")
19 | return next();
20 | }
21 | }
22 |
23 | module.exports= {
24 | checkForAuthentication,
25 | restrictTo
26 | };
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/models/url.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const urlSchema = new mongoose.Schema(
4 | {
5 | shortId : {
6 | type : String,
7 | required : true,
8 | unique: true,
9 | },
10 | redirectURL :{
11 | type : String,
12 | required : true,
13 | },
14 | visitHistory: [
15 | { timestamp : {
16 | type : Number
17 | }}
18 | ],
19 | createdBy : {
20 | type: mongoose.Schema.Types.ObjectId,
21 | ref: 'users'
22 | }
23 | } ,
24 | { timestamp : true }
25 | );
26 |
27 |
28 | const URL = mongoose.model("url" , urlSchema)
29 |
30 | module.exports = URL;
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/models/user.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const userSchema = new mongoose.Schema({
4 | name:{
5 | type: String,
6 | required : true,
7 | },
8 | email:{
9 | type:String,
10 | required: true,
11 | unquie : true,
12 | },
13 | password:{
14 | type: String,
15 | required: true,
16 | },
17 | role:{
18 | type: String,
19 | required:true,
20 | default:"NORMAL"
21 | }
22 |
23 |
24 |
25 | },{timestamps:true});
26 |
27 | const User = mongoose.model('user', userSchema);
28 |
29 | module.exports = User;
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "21_custom_url_shortener",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "nodemon index.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cookie-parser": "^1.4.6",
14 | "ejs": "^3.1.9",
15 | "express": "^4.18.3",
16 | "jsonwebtoken": "^9.0.2",
17 | "mongoose": "^8.2.1",
18 | "nanoid": "^3.3.7",
19 | "nodemon": "^3.1.0",
20 | "uuid": "^9.0.1"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/routes/staticRoute.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const URL = require('../models/url');
3 | const {restrictTo} = require("../middlewares/auth")
4 | const router = express.Router();
5 |
6 | router.get('/admin/urls',restrictTo(['ADMIN']), async(req , res)=>{
7 | const allurls = await URL.find({});
8 | return res.render("home",{
9 | urls:allurls,
10 | })
11 | })
12 |
13 | router.get('/',restrictTo(["NORMAL","ADMIN"]), async(req, res)=>{
14 | const allUrls = await URL.find({ createdBy : req.user._id});
15 | return res.render("home",{
16 | urls: allUrls,
17 | })
18 | })
19 |
20 |
21 | router.get('/signup', async(req , res)=>{
22 | return res.render("signup");
23 | })
24 |
25 | router.get('/login', async(req , res)=>{
26 | return res.render("login");
27 | })
28 |
29 |
30 |
31 | module.exports = router;
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/routes/url.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const {handleGenerateNewShortURL , handleGetAnalytics} = require("../controllers/url")
3 | const router = express.Router();
4 |
5 | router.post('/' , handleGenerateNewShortURL)
6 | router.get('/analytics/:shortId',handleGetAnalytics )
7 |
8 | module.exports = router;
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/routes/user.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const {handleUserLogin , handleUserSignup} = require("../controllers/user");
3 |
4 | const router = express.Router();
5 |
6 |
7 | router.post('/', handleUserSignup)
8 | router.post('/login',handleUserLogin)
9 |
10 | module.exports = router;
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/service/auth.js:
--------------------------------------------------------------------------------
1 | //Removing state and importing JWT
2 |
3 | const jwt = require("jsonwebtoken");
4 | const secret = "Ayush$123@$"
5 |
6 | function setUser( user){
7 | return jwt.sign({
8 | _id: user._id,
9 | email: user.email,
10 | role: user.role,
11 | }, secret);
12 | //assigning user object as a payload
13 | }
14 |
15 | function getUser(token){
16 | try {
17 | return jwt.verify(token, secret);
18 | } catch (error) {
19 | return null;
20 | }
21 |
22 | }
23 |
24 | module.exports={
25 | setUser,
26 | getUser
27 | };
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Home
7 |
12 |
13 |
14 | URL Shortner
15 | <% if(locals.id){
16 | %>
17 | URL Generated : http://localhost:8001/url/<%= id%>
18 | <%
19 | } %>
20 |
21 |
26 |
27 |
28 |
29 | <% if(locals.urls){
30 | %>
31 |
32 |
33 | S. no
34 | ShortID
35 | Redirect
36 | Clicks
37 |
38 |
39 | <% urls.forEach((url , index )=> {
40 | %>
41 |
42 | <%= index +1 %>
43 | <%= url.shortId %>
44 | <%= url.redirectURL %>
45 | <%= url.visitHistory.length %>
46 |
47 | <%
48 | });
49 | %>
50 |
51 |
52 | <%
53 | } %>
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/views/login.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Login
7 |
12 |
13 |
14 | Login
15 |
25 |
26 |
--------------------------------------------------------------------------------
/26_Authorization_in_NodeJS/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Sign Up
7 |
12 |
13 |
14 | Sign Up
15 |
27 |
28 |
--------------------------------------------------------------------------------
/27_Creating_Discord_Bot_in_NodeJS/command.js:
--------------------------------------------------------------------------------
1 | import { REST, Routes } from 'discord.js';
2 | const commands = [
3 | {
4 | name: 'create',
5 | description: 'Create short url',
6 | },
7 | ];
8 |
9 | const rest = new REST({ version: '10' }).setToken(SECRET_KEY);
10 |
11 | try {
12 | console.log('Started refreshing application (/) commands.');
13 |
14 | await rest.put(Routes.applicationCommands('1224397427445071902'), { body: commands });
15 |
16 | console.log('Successfully reloaded application (/) commands.');
17 | } catch (error) {
18 | console.error(error);
19 | }
--------------------------------------------------------------------------------
/27_Creating_Discord_Bot_in_NodeJS/index.js:
--------------------------------------------------------------------------------
1 | import { Client, GatewayIntentBits } from 'discord.js';
2 | const client = new Client(
3 | {
4 | intents: [
5 | GatewayIntentBits.Guilds,
6 | GatewayIntentBits.GuildMessages,
7 | GatewayIntentBits.MessageContent
8 | ] });
9 |
10 |
11 | client.on('messageCreate',message =>{
12 | // console.log(message.content);
13 | if(message.author.bot) return;
14 | message.reply({
15 | content:"Hii from Bot!"
16 | })
17 | if(message.content.startsWith('create')){
18 | const url = message.content.split("create")[1];
19 | return message.reply({
20 | content:"Generating Short ID for "+url,
21 | })
22 | }
23 | })
24 |
25 | client.on('interactionCreate',interaction =>{
26 | interaction.reply("Pong!");
27 | })
28 |
29 | client.login(SECRET_KEY);
--------------------------------------------------------------------------------
/27_Creating_Discord_Bot_in_NodeJS/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "27_creating_discord_bot_in_nodejs",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "type": "module",
7 | "scripts": {
8 | "test": "echo \"Error: no test specified\" && exit 1",
9 | "start": "node index"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "discord.js": "^14.14.1"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/28_Uploding_Files_with_NodeJS_and_Multer/Readme.md:
--------------------------------------------------------------------------------
1 | ## Uploading Files with NodeJS and Multer
2 |
3 | - installed EJS , Express and Multer Packages
4 | - Created a Form in ejs
5 | - Added action="folder" , method+"post" and erictype="multipart/form-data" in form
6 | - A form can have data + files so must use enctype.
7 | - Use middileware `express.urlencoded({}) which helps to parse the form data.
8 | - Using disk storage to get full control on files.
9 | - We can store `req.file.path` to the database to get the files easily.
10 | - We use `upload.single` to upload single image.
11 | - We can use `upload.array` and `upload.fields` to upload multiple files.
--------------------------------------------------------------------------------
/28_Uploding_Files_with_NodeJS_and_Multer/index.js:
--------------------------------------------------------------------------------
1 | const path = require("path");
2 | const express = require('express')
3 | const multer = require('multer')
4 |
5 | const app = express();
6 | const PORT = 8000;
7 |
8 | app.use(express.json());
9 | app.use(express.urlencoded({extended:false}))//helps to pass form data
10 |
11 | const storage = multer.diskStorage({
12 | destination:function(req, file , cb){
13 | return cb(null , "./uploads")
14 | // error , foldername
15 | },
16 | filename:function(req, file, cb){
17 | return cb(null , `${Date.now()}-${file.originalname}`)
18 | // error filename
19 | },
20 | })
21 |
22 | const upload = multer({storage:storage});
23 |
24 | app.set("view engine","ejs")
25 | app.set("views",path.resolve("./views"));
26 |
27 | app.get('/',(req,res)=>{
28 | return res.render("homepage")
29 | })
30 |
31 | app.post('/upload',upload.single("profileImage"),(req,res)=>{
32 | console.log(req.body); //no text field -> Null
33 | console.log(req.file);
34 |
35 | return res.redirect("/");
36 | })
37 | app.listen(PORT,()=>{
38 | console.log(`Server started at PORT:${PORT}`);
39 | })
--------------------------------------------------------------------------------
/28_Uploding_Files_with_NodeJS_and_Multer/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "28_uploding_files_with_nodejs_and_multer",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "ejs": "^3.1.9",
13 | "express": "^4.19.2",
14 | "multer": "^1.4.5-lts.1"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/28_Uploding_Files_with_NodeJS_and_Multer/uploads/1712197245796-github (2).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/28_Uploding_Files_with_NodeJS_and_Multer/uploads/1712197245796-github (2).png
--------------------------------------------------------------------------------
/28_Uploding_Files_with_NodeJS_and_Multer/views/homepage.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Upload Files
7 |
8 |
9 |
13 |
14 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/Readme.md:
--------------------------------------------------------------------------------
1 | # Blogging App
2 |
3 | - `--dev` use to make Development dependency.
4 | - Dev dependency is required only in development enviornment.
5 | - Ex: `npm i nodemon --dev`
6 | - It will not be used in Production enviornment.
7 | - We haave used `Partials` Folder Which includes all the files which are partial for many other files.
8 | - Steps :
9 | - Created Models
10 | - Created Views
11 | - Created Router to handle request
12 | - Hashed the password using crypto library
13 | - Worked on Signup page
14 | - Worked on Signin page
15 | - Signup and signin done
16 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/index.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const path = require('path');
3 | const ejs = require('ejs')
4 | const mongoose = require('mongoose')
5 |
6 | mongoose.connect('mongodb://127.0.0.1:27017/blogify')
7 | .then((e)=> console.log("MongoDB Connected"))
8 |
9 | const userRoute = require('./routes/user')
10 | const app = express();
11 | const PORT = 800;
12 |
13 | app.set("view engine","ejs")
14 | app.set("views", path.resolve( "views"));
15 |
16 | app.use(express.urlencoded({extended:false}))
17 |
18 | app.get('/',(req,res)=>{
19 | return res.render('home');
20 | })
21 |
22 | app.use('/user',userRoute)
23 | // If any request start with /user then use `userRoute`
24 |
25 | app.listen(PORT , ()=>console.log(`Server started at PORT:${PORT}`));
26 |
27 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/models/user.js:
--------------------------------------------------------------------------------
1 | const {Schema,model}= require('mongoose');
2 | const { createHmac ,randomBytes } = require('node:crypto');
3 |
4 | const userSchema = new Schema(
5 | {
6 | fullName:{
7 | type:'String',
8 | required : true
9 | },
10 | email:{
11 | type:String,
12 | required:true,
13 | unique:true
14 | },
15 | salt:{
16 | type:String,
17 | }
18 | ,
19 | password:{
20 | type:String,
21 | requied:true
22 | },
23 | profileImageURL:{
24 | type:String,
25 | default:'/images/default.png',
26 | },
27 | role:{
28 | type:String,
29 | enum:["USER","ADMIN"],
30 | default:"USER",
31 | }
32 | },
33 | {timestamp: true}
34 | );
35 |
36 | //using pre middleware of mangoose
37 | userSchema.pre('save',function(){
38 | const user = this;
39 | if(!user.isModified("password")) return;
40 | const salt = randomBytes(16).toString(); //random string
41 | const hashedPassword = createHmac('sha256',salt)
42 | .update(user.password)
43 | .digest("hex");
44 | this.salt = salt;
45 | this.password=hashedPassword;
46 |
47 | })
48 |
49 | //making function
50 | userSchema.static('matchPassword',async function(email,password){
51 | const user =await this.findOne({email});
52 | if(!user) throw new Error('User not found !');
53 |
54 | console.log(user);
55 | const salt = user.salt;
56 | const hashedPassword = user.password;
57 |
58 | const userProvideHash = createHmac("sha256",salt)
59 | .update(password)
60 | .digest("hex")
61 |
62 | if(hashedPassword !== userProvideHash){
63 | throw new Error("Incorrect Password!");
64 | }
65 | return user;
66 |
67 | })
68 |
69 | const User = model('user',userSchema)
70 |
71 | module.exports= User;
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "29_setting_up_project-nodejs_blogging_app",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node index.js",
9 | "dev": "nodemon index.js"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "ejs": "^3.1.9",
15 | "express": "^4.19.2",
16 | "mongoose": "^8.3.0",
17 | "nodemon": "^3.1.0"
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/public/images/deafult.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/29_Setting_Up_Project-NodeJS_Blogging_App/public/images/deafult.jpg
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/routes/user.js:
--------------------------------------------------------------------------------
1 | const {Router} = require('express');
2 | const User = require('../models/user')
3 | const router = Router();
4 |
5 | router.get('/signin',(req,res)=>{
6 | return res.render("signin")
7 | })
8 | router.get('/signup',(req,res)=>{
9 | return res.render("signup");
10 | })
11 | router.post('/signup',async (req,res)=>{
12 | const {fullName , password , email } = req.body;
13 | await User.create({
14 | fullName,
15 | email,
16 | password
17 | });
18 | return res.redirect('/');
19 | })
20 |
21 | router.post('/signin',async(req,res)=>{
22 | const { password , email } = req.body;
23 | const user =await User.matchPassword(email,password);
24 | console.log("User",user);
25 | return res.redirect('/')
26 |
27 | })
28 | module.exports=router;
29 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Homepage
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 | <%- include('./partials/scripts') %>
11 |
12 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/views/partials/head.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/views/partials/nav.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Blogify
4 |
5 |
6 |
7 |
8 |
9 |
10 | Home
11 |
12 |
13 | Add Blog
14 |
15 |
16 |
19 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/views/partials/scripts.ejs:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/views/signin.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signin
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
26 | <%- include('./partials/scripts') %>
27 |
28 |
--------------------------------------------------------------------------------
/29_Setting_Up_Project-NodeJS_Blogging_App/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signup
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
30 | <%- include('./partials/scripts') %>
31 |
32 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/Readme.md:
--------------------------------------------------------------------------------
1 | # Setting up Blogging App
2 |
3 | - `--dev` use to make Development dependency.
4 | - Dev dependency is required only in development enviornment.
5 | - Ex: `npm i nodemon --dev`
6 | - It will not be used in Production enviornment.
7 | - We haave used `Partials` Folder Which includes all the files which are partial for many other files.
8 | - Steps :
9 | - Created Models
10 | - Created Views
11 | - Created Router to handle request
12 | - Hashed the password using crypto library
13 | - Worked on Signup page
14 | - Worked on Signin page
15 | - Signup and signin done
16 |
17 |
18 | # Authentication
19 |
20 | - Created a JWT Token
21 | - Creation and valiation of JWT token
22 | - made payload for valid user
23 | - Saved in localstorage
24 | - Created a middleware to check for authentication cookie
25 | - Installed `cookie-parser` library and used it
26 | - Made a route for clear cookie(logout)
27 | - set the token with full name and displayed the full name at username by me
28 | - created blog schema and model
29 | - Made Blog Router And Schema
30 | - Created a blog page
31 | - Stored the blog in database
32 | - Used multer to store the image
33 | - Used `express.static(path.resolve('./public')` middleware to get access to static files(blog image)
34 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/index.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const path = require('path');
3 | const ejs = require('ejs')
4 | const mongoose = require('mongoose')
5 | const cookieParser = require('cookie-parser')
6 |
7 | mongoose.connect('mongodb://127.0.0.1:27017/blogify')
8 | .then((e)=> console.log("MongoDB Connected"))
9 |
10 | const Blog = require('./models/blog')
11 |
12 | const userRoute = require('./routes/user')
13 | const blogRoute = require('./routes/blog')
14 |
15 | const { checkForAuthenticationCookie } = require('./middlewares/authentication');
16 | const app = express();
17 | const PORT = 800;
18 |
19 | app.set("view engine","ejs")
20 | app.set("views", path.resolve( "views"));
21 |
22 | //middleware
23 | app.use(express.urlencoded({extended:false}))
24 | app.use(cookieParser())
25 | app.use(checkForAuthenticationCookie("token"))
26 | app.use(express.static(path.resolve('./public')))
27 |
28 | app.get('/',async(req,res)=>{
29 | const allBlogs = await Blog.find({});
30 | return res.render('home',{
31 | user: req.user,
32 | blogs: allBlogs
33 | });
34 | })
35 |
36 | app.use('/user',userRoute)
37 | // If any request start with /user then use `userRoute`
38 | app.use('/blog',blogRoute)
39 |
40 |
41 |
42 |
43 | app.listen(PORT , ()=>console.log(`Server started at PORT:${PORT}`));
44 |
45 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/middlewares/authentication.js:
--------------------------------------------------------------------------------
1 | const { validateToken } = require("../services/authentication");
2 |
3 | function checkForAuthenticationCookie(cookieName){
4 | return (req , res , next)=>{
5 | const tokenCookieValue = req.cookies[cookieName];
6 | if(!tokenCookieValue){
7 | return next();
8 | }
9 |
10 | try{
11 | const userPayload = validateToken(tokenCookieValue);
12 | req.user = userPayload;
13 | return next();
14 | }catch(error){}
15 |
16 | }
17 |
18 | }
19 |
20 | module.exports={
21 | checkForAuthenticationCookie,
22 | }
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/models/blog.js:
--------------------------------------------------------------------------------
1 | const {Schema , model} = require('mongoose')
2 |
3 |
4 | const blogSchema = new Schema({
5 | title:{
6 | type: String,
7 | required:true
8 | },
9 | body:{
10 | type: String,
11 | required: true
12 | },
13 | coverImageURL :{
14 | type:String,
15 | required: false,
16 | },
17 | createdBy:{
18 | type: Schema.Types.ObjectId,
19 | ref : "user",
20 | },
21 | }, { timestamps : true}
22 | )
23 |
24 | const blog = model('blog',blogSchema);
25 |
26 | module.exports = blog;
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/models/user.js:
--------------------------------------------------------------------------------
1 | const {Schema,model}= require('mongoose');
2 | const { createHmac ,randomBytes } = require('node:crypto');
3 | const {createTokenForUser} = require('../services/authentication')
4 |
5 | const userSchema = new Schema(
6 | {
7 | fullName:{
8 | type:'String',
9 | required : true
10 | },
11 | email:{
12 | type:String,
13 | required:true,
14 | unique:true
15 | },
16 | salt:{
17 | type:String,
18 | }
19 | ,
20 | password:{
21 | type:String,
22 | requied:true
23 | },
24 | profileImageURL:{
25 | type:String,
26 | default:'/images/default.png',
27 | },
28 | role:{
29 | type:String,
30 | enum:["USER","ADMIN"],
31 | default:"USER",
32 | }
33 | },
34 | {timestamp: true}
35 | );
36 |
37 | //using pre middleware of mangoose
38 | userSchema.pre('save',function(){
39 | const user = this;
40 | if(!user.isModified("password")) return;
41 | const salt = randomBytes(16).toString(); //random string
42 | const hashedPassword = createHmac('sha256',salt)
43 | .update(user.password)
44 | .digest("hex");
45 | this.salt = salt;
46 | this.password=hashedPassword;
47 |
48 | })
49 |
50 | //making function
51 | userSchema.static('matchPasswordAndGenerateToken',async function(email,password){
52 | const user =await this.findOne({email});
53 | if(!user) throw new Error('User not found !');
54 |
55 | console.log(user);
56 | const salt = user.salt;
57 | const hashedPassword = user.password;
58 |
59 | const userProvideHash = createHmac("sha256",salt)
60 | .update(password)
61 | .digest("hex")
62 |
63 | if(hashedPassword !== userProvideHash){
64 | throw new Error("Incorrect Password!");
65 | }
66 | const token = createTokenForUser(user)
67 | return token;
68 | })
69 |
70 | const User = model('user',userSchema)
71 |
72 | module.exports= User;
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "29_setting_up_project-nodejs_blogging_app",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node index.js",
9 | "dev": "nodemon index.js"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "cookie-parser": "^1.4.6",
15 | "ejs": "^3.1.9",
16 | "express": "^4.19.2",
17 | "jsonwebtoken": "^9.0.2",
18 | "mongoose": "^8.3.0",
19 | "multer": "^1.4.5-lts.1",
20 | "nodemon": "^3.1.0"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/public/images/deafult.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/30_Setting_up_Authentication-NodeJS_Blogging_App/public/images/deafult.jpg
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/public/uploads/1712311193510-Screenshot (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/30_Setting_up_Authentication-NodeJS_Blogging_App/public/uploads/1712311193510-Screenshot (1).png
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/public/uploads/1712311768043-Screenshot (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/30_Setting_up_Authentication-NodeJS_Blogging_App/public/uploads/1712311768043-Screenshot (1).png
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/routes/blog.js:
--------------------------------------------------------------------------------
1 | const {Router} = require('express')
2 | const multer = require('multer')
3 | const path = require('path')
4 | const router = Router();
5 | const Blog = require('../models/blog')
6 |
7 | const storage = multer.diskStorage({
8 | destination: function (req, file, cb) {
9 | cb(null, path.resolve(`./public/uploads/`))
10 | },
11 | filename: function (req, file, cb) {
12 | const fileName = `${Date.now()}-${file.originalname}`
13 | cb(null,fileName);
14 | }
15 | })
16 | const upload = multer({ storage: storage })
17 |
18 | router.get('/add-new', (req, res)=>{
19 | return res.render('addBlog',{
20 | user: req.user,
21 | })
22 | })
23 |
24 | router.post('/', upload.single('coverImage'), async(req, res)=>{
25 | const {title , body} = req.body;
26 | const blog = await Blog.create({
27 | body,
28 | title,
29 | createdBy: req.user._id,
30 | coverImageURL: `/uploads/${req.file.filename}`
31 | })
32 | return res.redirect(`/blog/${blog._id}`)
33 | })
34 |
35 | module.exports = router;
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/routes/user.js:
--------------------------------------------------------------------------------
1 | const {Router} = require('express');
2 | const User = require('../models/user')
3 | const router = Router();
4 |
5 | router.get('/signin',(req,res)=>{
6 | return res.render("signin")
7 | })
8 | router.get('/signup',(req,res)=>{
9 | return res.render("signup");
10 | })
11 | router.post('/signup',async (req,res)=>{
12 | const {fullName , password , email } = req.body;
13 | await User.create({
14 | fullName,
15 | email,
16 | password
17 | });
18 | return res.redirect('/');
19 | })
20 |
21 | router.post('/signin',async(req,res)=>{
22 | const { password , email } = req.body;
23 | try {
24 | const token =await User.matchPasswordAndGenerateToken(email,password);
25 | console.log("Token",token);
26 | return res.cookie('token',token).redirect('/');
27 | } catch (error) {
28 | return res.render('signin',{
29 | error:"Incorrect Email or Password",
30 | });
31 | }
32 |
33 |
34 | })
35 |
36 | router.get('/logout',(req, res)=>{
37 | res.clearCookie('token').redirect('/');
38 | })
39 | module.exports=router;
40 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/services/authentication.js:
--------------------------------------------------------------------------------
1 | const JWT = require('jsonwebtoken')
2 |
3 | const secret = "$uperMan@123";
4 |
5 | function createTokenForUser(user){
6 | const payload = {
7 | _id : user._id,
8 | email: user.email,
9 | profileImageURL : user.profileImageURL,
10 | role: user.role,
11 | fullName : user.fullName,
12 | };
13 | const token = JWT.sign(payload,secret);
14 | return token;
15 | }
16 |
17 | function validateToken(token){
18 | const payload = JWT.verify(token , secret);
19 | return payload;
20 | }
21 |
22 | module.exports ={
23 | createTokenForUser,
24 | validateToken
25 | }
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/views/addBlog.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Add New Blog Page
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
29 | <%- include('./partials/scripts') %>
30 |
31 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Homepage
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 | <% blogs.forEach(blog => { %>
12 |
13 |
14 |
15 |
<%= blog.title %>
16 |
View
17 |
18 |
19 |
20 | <% }) %>
21 |
22 |
23 | <%- include('./partials/scripts') %>
24 |
25 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/views/partials/head.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/views/partials/nav.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Blogify
4 |
5 |
6 |
7 |
8 |
9 |
10 | Home
11 |
12 | <% if (locals.user) { %>
13 |
14 | Add Blog
15 |
16 |
17 |
20 |
23 |
24 | <% }else { %>
25 |
26 | Create Account
27 |
28 |
29 |
30 |
31 | Signin
32 |
33 |
34 | <% } %>
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | <% if(locals.error){ %>
43 |
44 |
45 | <%= locals.error %>
46 |
47 |
48 |
49 | <% }
50 | %>
51 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/views/partials/scripts.ejs:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/views/signin.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signin
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 |
Email address
14 |
15 |
We'll never share your email with anyone else.
16 |
17 |
18 |
19 | Password
20 |
21 |
22 |
23 | Submit
24 |
25 |
26 | <%- include('./partials/scripts') %>
27 |
28 |
--------------------------------------------------------------------------------
/30_Setting_up_Authentication-NodeJS_Blogging_App/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signup
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 | Full Name
14 |
15 |
16 |
17 |
Email address
18 |
19 |
We'll never share your email with anyone else.
20 |
21 |
22 |
23 | Password
24 |
25 |
26 |
27 | Submit
28 |
29 |
30 | <%- include('./partials/scripts') %>
31 |
32 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/Readme.md:
--------------------------------------------------------------------------------
1 | # Setting up Blogging App
2 |
3 | - `--dev` use to make Development dependency.
4 | - Dev dependency is required only in development enviornment.
5 | - Ex: `npm i nodemon --dev`
6 | - It will not be used in Production enviornment.
7 | - We haave used `Partials` Folder Which includes all the files which are partial for many other files.
8 | - Steps :
9 | - Created Models
10 | - Created Views
11 | - Created Router to handle request
12 | - Hashed the password using crypto library
13 | - Worked on Signup page
14 | - Worked on Signin page
15 | - Signup and signin done
16 |
17 |
18 | # Authentication
19 |
20 | - Created a JWT Token
21 | - Creation and valiation of JWT token
22 | - made payload for valid user
23 | - Saved in localstorage
24 | - Created a middleware to check for authentication cookie
25 | - Installed `cookie-parser` library and used it
26 | - Made a route for clear cookie(logout)
27 | - set the token with full name and displayed the full name at username by me
28 | - created blog schema and model
29 | - Made Blog Router And Schema
30 | - Created a blog page
31 | - Stored the blog in database
32 | - Used multer to store the image
33 | - Used `express.static(path.resolve('./public')` middleware to get access to static files(blog image)
34 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/index.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const path = require('path');
3 | const ejs = require('ejs')
4 | const mongoose = require('mongoose')
5 | const cookieParser = require('cookie-parser')
6 |
7 | mongoose.connect('mongodb://127.0.0.1:27017/blogify')
8 | .then((e)=> console.log("MongoDB Connected"))
9 |
10 | const Blog = require('./models/blog')
11 |
12 | const userRoute = require('./routes/user')
13 | const blogRoute = require('./routes/blog')
14 |
15 | const { checkForAuthenticationCookie } = require('./middlewares/authentication');
16 | const app = express();
17 | const PORT = 800;
18 |
19 | app.set("view engine","ejs")
20 | app.set("views", path.resolve( "views"));
21 |
22 | //middleware
23 | app.use(express.urlencoded({extended:false}))
24 | app.use(cookieParser())
25 | app.use(checkForAuthenticationCookie("token"))
26 | app.use(express.static(path.resolve('./public')))
27 |
28 | app.get('/',async(req,res)=>{
29 | const allBlogs = await Blog.find({});
30 | return res.render('home',{
31 | user: req.user,
32 | blogs: allBlogs
33 | });
34 | })
35 |
36 | app.use('/user',userRoute)
37 | // If any request start with /user then use `userRoute`
38 | app.use('/blog',blogRoute)
39 |
40 |
41 |
42 |
43 | app.listen(PORT , ()=>console.log(`Server started at PORT:${PORT}`));
44 |
45 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/middlewares/authentication.js:
--------------------------------------------------------------------------------
1 | const { validateToken } = require("../services/authentication");
2 |
3 | function checkForAuthenticationCookie(cookieName){
4 | return (req , res , next)=>{
5 | const tokenCookieValue = req.cookies[cookieName];
6 | if(!tokenCookieValue){
7 | return next();
8 | }
9 |
10 | try{
11 | const userPayload = validateToken(tokenCookieValue);
12 | req.user = userPayload;
13 | return next();
14 | }catch(error){}
15 |
16 | }
17 |
18 | }
19 |
20 | module.exports={
21 | checkForAuthenticationCookie,
22 | }
--------------------------------------------------------------------------------
/31_Complete_Blog_App/models/blog.js:
--------------------------------------------------------------------------------
1 | const {Schema , model} = require('mongoose')
2 |
3 |
4 | const blogSchema = new Schema({
5 | title:{
6 | type: String,
7 | required:true
8 | },
9 | body:{
10 | type: String,
11 | required: true
12 | },
13 | coverImageURL :{
14 | type:String,
15 | required: false,
16 | },
17 | createdBy:{
18 | type: Schema.Types.ObjectId,
19 | ref : "user",
20 | },
21 | }, { timestamps : true}
22 | )
23 |
24 | const blog = model('blog',blogSchema);
25 |
26 | module.exports = blog;
--------------------------------------------------------------------------------
/31_Complete_Blog_App/models/comments.js:
--------------------------------------------------------------------------------
1 | const {Schema , model} = require('mongoose')
2 |
3 | const commentSchema = new Schema({
4 | content: {
5 | type: String,
6 | required : true,
7 | },
8 | blogId:{
9 | type: Schema.Types.ObjectId,
10 | ref:"blog"
11 | },
12 | createdBy:{
13 | type: Schema.Types.ObjectId,
14 | ref:"user",
15 | },
16 | }, {timestamps:true})
17 |
18 | const Comment = model("comment",commentSchema);
19 |
20 | module.exports = Comment;
--------------------------------------------------------------------------------
/31_Complete_Blog_App/models/user.js:
--------------------------------------------------------------------------------
1 | const {Schema,model}= require('mongoose');
2 | const { createHmac ,randomBytes } = require('node:crypto');
3 | const {createTokenForUser} = require('../services/authentication')
4 |
5 | const userSchema = new Schema(
6 | {
7 | fullName:{
8 | type:'String',
9 | required : true
10 | },
11 | email:{
12 | type:String,
13 | required:true,
14 | unique:true
15 | },
16 | salt:{
17 | type:String,
18 | }
19 | ,
20 | password:{
21 | type:String,
22 | requied:true
23 | },
24 | profileImageURL:{
25 | type:String,
26 | default:'/images/default.png',
27 | },
28 | role:{
29 | type:String,
30 | enum:["USER","ADMIN"],
31 | default:"USER",
32 | }
33 | },
34 | {timestamp: true}
35 | );
36 |
37 | //using pre middleware of mangoose
38 | userSchema.pre('save',function(){
39 | const user = this;
40 | if(!user.isModified("password")) return;
41 | const salt = randomBytes(16).toString(); //random string
42 | const hashedPassword = createHmac('sha256',salt)
43 | .update(user.password)
44 | .digest("hex");
45 | this.salt = salt;
46 | this.password=hashedPassword;
47 |
48 | })
49 |
50 | //making function
51 | userSchema.static('matchPasswordAndGenerateToken',async function(email,password){
52 | const user =await this.findOne({email});
53 | if(!user) throw new Error('User not found !');
54 |
55 | console.log(user);
56 | const salt = user.salt;
57 | const hashedPassword = user.password;
58 |
59 | const userProvideHash = createHmac("sha256",salt)
60 | .update(password)
61 | .digest("hex")
62 |
63 | if(hashedPassword !== userProvideHash){
64 | throw new Error("Incorrect Password!");
65 | }
66 | const token = createTokenForUser(user)
67 | return token;
68 | })
69 |
70 | const User = model('user',userSchema)
71 |
72 | module.exports= User;
--------------------------------------------------------------------------------
/31_Complete_Blog_App/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "29_setting_up_project-nodejs_blogging_app",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node index.js",
9 | "dev": "nodemon index.js"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "cookie-parser": "^1.4.6",
15 | "ejs": "^3.1.9",
16 | "express": "^4.19.2",
17 | "jsonwebtoken": "^9.0.2",
18 | "mongoose": "^8.3.0",
19 | "multer": "^1.4.5-lts.1",
20 | "nodemon": "^3.1.0"
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/public/images/default.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/31_Complete_Blog_App/public/images/default.png
--------------------------------------------------------------------------------
/31_Complete_Blog_App/public/uploads/1712311193510-Screenshot (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/31_Complete_Blog_App/public/uploads/1712311193510-Screenshot (1).png
--------------------------------------------------------------------------------
/31_Complete_Blog_App/public/uploads/1712311768043-Screenshot (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/31_Complete_Blog_App/public/uploads/1712311768043-Screenshot (1).png
--------------------------------------------------------------------------------
/31_Complete_Blog_App/public/uploads/1712428496751-1_A7PQiIdB5buNa0mgq063Xg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/31_Complete_Blog_App/public/uploads/1712428496751-1_A7PQiIdB5buNa0mgq063Xg.png
--------------------------------------------------------------------------------
/31_Complete_Blog_App/public/uploads/1712429054876-piyu.avif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/31_Complete_Blog_App/public/uploads/1712429054876-piyu.avif
--------------------------------------------------------------------------------
/31_Complete_Blog_App/public/uploads/1712429113684-fire.avif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/31_Complete_Blog_App/public/uploads/1712429113684-fire.avif
--------------------------------------------------------------------------------
/31_Complete_Blog_App/routes/blog.js:
--------------------------------------------------------------------------------
1 | const {Router} = require('express')
2 | const multer = require('multer')
3 | const path = require('path')
4 | const router = Router();
5 | const Blog = require('../models/blog');
6 | const Comment = require('../models/comments');
7 |
8 | const storage = multer.diskStorage({
9 | destination: function (req, file, cb) {
10 | cb(null, path.resolve(`./public/uploads/`))
11 | },
12 | filename: function (req, file, cb) {
13 | const fileName = `${Date.now()}-${file.originalname}`
14 | cb(null,fileName);
15 | }
16 | })
17 | const upload = multer({ storage: storage })
18 |
19 | router.get('/add-new', (req, res)=>{
20 | return res.render('addBlog',{
21 | user: req.user,
22 | })
23 | })
24 |
25 | router.post('/', upload.single('coverImage'), async(req, res)=>{
26 | const {title , body} = req.body;
27 | const blog = await Blog.create({
28 | body,
29 | title,
30 | createdBy: req.user._id,
31 | coverImageURL: `/uploads/${req.file.filename}`
32 | })
33 | return res.redirect(`/blog/${blog._id}`)
34 | })
35 |
36 | router.get('/:id',async(req, res)=>{
37 | const blog = await Blog.findById(req.params.id).populate("createdBy");
38 | const comments = await Comment.find({blogId: req.params.id}).populate("createdBy")
39 | console.log("blog: ",blog)
40 | return res.render('blog',{
41 | user: req.user,
42 | blog,
43 | comments,
44 | })
45 | })
46 |
47 | router.post('/comment/:blogId',async(req,res)=>{
48 | await Comment.create({
49 | content: req.body.content,
50 | blogId: req.params.blogId,
51 | createdBy: req.user._id,
52 | })
53 | return res.redirect(`/blog/${req.params.blogId}`)
54 |
55 | })
56 | module.exports = router;
--------------------------------------------------------------------------------
/31_Complete_Blog_App/routes/user.js:
--------------------------------------------------------------------------------
1 | const {Router} = require('express');
2 | const User = require('../models/user')
3 | const router = Router();
4 |
5 | router.get('/signin',(req,res)=>{
6 | return res.render("signin")
7 | })
8 | router.get('/signup',(req,res)=>{
9 | return res.render("signup");
10 | })
11 | router.post('/signup',async (req,res)=>{
12 | const {fullName , password , email } = req.body;
13 | await User.create({
14 | fullName,
15 | email,
16 | password
17 | });
18 | return res.redirect('/');
19 | })
20 |
21 | router.post('/signin',async(req,res)=>{
22 | const { password , email } = req.body;
23 | try {
24 | const token =await User.matchPasswordAndGenerateToken(email,password);
25 | console.log("Token",token);
26 | return res.cookie('token',token).redirect('/');
27 | } catch (error) {
28 | return res.render('signin',{
29 | error:"Incorrect Email or Password",
30 | });
31 | }
32 |
33 |
34 | })
35 |
36 | router.get('/logout',(req, res)=>{
37 | res.clearCookie('token').redirect('/');
38 | })
39 | module.exports=router;
40 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/services/authentication.js:
--------------------------------------------------------------------------------
1 | const JWT = require('jsonwebtoken')
2 |
3 | const secret = "$uperMan@123";
4 |
5 | function createTokenForUser(user){
6 | const payload = {
7 | _id : user._id,
8 | email: user.email,
9 | profileImageURL : user.profileImageURL,
10 | role: user.role,
11 | fullName : user.fullName,
12 | };
13 | const token = JWT.sign(payload,secret);
14 | return token;
15 | }
16 |
17 | function validateToken(token){
18 | const payload = JWT.verify(token , secret);
19 | return payload;
20 | }
21 |
22 | module.exports ={
23 | createTokenForUser,
24 | validateToken
25 | }
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/addBlog.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Add New Blog Page
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 | Blog Title
14 |
15 |
16 |
17 | Cover Image
18 |
19 |
20 |
21 |
22 | Write Your Blog
23 |
24 |
25 | Button
26 |
27 |
28 |
29 | <%- include('./partials/scripts') %>
30 |
31 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/blog.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Homepage
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
<%= blog.title %>
12 |
13 |
<%= blog.body %>
14 |
15 |
16 |
17 |
18 | <%= blog.createdBy.fullName %>
19 |
20 |
21 |
Comments (<%= comments.length %>)
22 | <% if (locals.user) { %>
23 |
24 |
25 |
26 |
27 | Add
28 |
29 | <% } %>
30 |
31 | <% comments.forEach(comment => { %>
32 |
33 |
34 | <%= comment.createdBy.fullName %>
35 |
<%= comment.content %>
36 |
37 | <% }) %>
38 |
39 |
40 |
41 | <%- include('./partials/scripts') %>
42 |
43 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Homepage
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 | <% blogs.forEach(blog => { %>
12 |
13 |
14 |
15 |
16 |
<%= blog.title %>
17 |
View
18 |
19 |
20 |
21 |
22 |
23 | <% }) %>
24 |
25 |
26 | <%- include('./partials/scripts') %>
27 |
28 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/partials/head.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/partials/nav.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Blogify
4 |
5 |
6 |
7 |
8 |
9 |
10 | Home
11 |
12 | <% if (locals.user) { %>
13 |
14 | Add Blog
15 |
16 |
17 |
20 |
23 |
24 | <% }else { %>
25 |
26 | Create Account
27 |
28 |
29 |
30 |
31 | Signin
32 |
33 |
34 | <% } %>
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | <% if(locals.error){ %>
43 |
44 |
45 | <%= locals.error %>
46 |
47 |
48 |
49 | <% }
50 | %>
51 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/partials/scripts.ejs:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/signin.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signin
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 |
Email address
14 |
15 |
We'll never share your email with anyone else.
16 |
17 |
18 |
19 | Password
20 |
21 |
22 |
23 | Submit
24 |
25 |
26 | <%- include('./partials/scripts') %>
27 |
28 |
--------------------------------------------------------------------------------
/31_Complete_Blog_App/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signup
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 | Full Name
14 |
15 |
16 |
17 |
Email address
18 |
19 |
We'll never share your email with anyone else.
20 |
21 |
22 |
23 | Password
24 |
25 |
26 |
27 | Submit
28 |
29 |
30 | <%- include('./partials/scripts') %>
31 |
32 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/.env:
--------------------------------------------------------------------------------
1 | MONGO_URL=mongodb://127.0.0.1:27017/blogify
2 | PORT=8000
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/Readme.md:
--------------------------------------------------------------------------------
1 | ## Deploy NodeJS App to Cloud
2 |
3 | - We can't set `PORT` for App on the server by own.
4 | - We need a enviournment variable i.e. Dynamic Variable.
5 | - Enviornment variable is set by cloud.
6 | - `process.env.Variable_Name`
7 | - For cloud sever make sure you have start script `"start": "node app.js"`
8 | - For Node.js, the main file is typically app.js
9 | -
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/app.js:
--------------------------------------------------------------------------------
1 | require('dotenv').config()
2 |
3 | const express = require('express');
4 | const path = require('path');
5 | const ejs = require('ejs')
6 | const mongoose = require('mongoose')
7 | const cookieParser = require('cookie-parser')
8 |
9 | mongoose.connect(process.env.MONGO_URL)
10 | .then((e)=> console.log("MongoDB Connected"))
11 |
12 | const Blog = require('./models/blog')
13 |
14 | const userRoute = require('./routes/user')
15 | const blogRoute = require('./routes/blog')
16 |
17 | const { checkForAuthenticationCookie } = require('./middlewares/authentication');
18 | const app = express();
19 | const PORT = process.env.PORT || 8000;
20 |
21 | app.set("view engine","ejs")
22 | app.set("views", path.resolve( "views"));
23 |
24 | //middleware
25 | app.use(express.urlencoded({extended:false}))
26 | app.use(cookieParser())
27 | app.use(checkForAuthenticationCookie("token"))
28 | app.use(express.static(path.resolve('./public')))
29 |
30 | app.get('/',async(req,res)=>{
31 | const allBlogs = await Blog.find({});
32 | return res.render('home',{
33 | user: req.user,
34 | blogs: allBlogs
35 | });
36 | })
37 |
38 | app.use('/user',userRoute)
39 | // If any request start with /user then use `userRoute`
40 | app.use('/blog',blogRoute)
41 |
42 |
43 |
44 |
45 | app.listen(PORT , ()=>console.log(`Server started at PORT:${PORT}`));
46 |
47 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/middlewares/authentication.js:
--------------------------------------------------------------------------------
1 | const { validateToken } = require("../services/authentication");
2 |
3 | function checkForAuthenticationCookie(cookieName){
4 | return (req , res , next)=>{
5 | const tokenCookieValue = req.cookies[cookieName];
6 | if(!tokenCookieValue){
7 | return next();
8 | }
9 |
10 | try{
11 | const userPayload = validateToken(tokenCookieValue);
12 | req.user = userPayload;
13 | return next();
14 | }catch(error){}
15 |
16 | }
17 |
18 | }
19 |
20 | module.exports={
21 | checkForAuthenticationCookie,
22 | }
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/models/blog.js:
--------------------------------------------------------------------------------
1 | const {Schema , model} = require('mongoose')
2 |
3 |
4 | const blogSchema = new Schema({
5 | title:{
6 | type: String,
7 | required:true
8 | },
9 | body:{
10 | type: String,
11 | required: true
12 | },
13 | coverImageURL :{
14 | type:String,
15 | required: false,
16 | },
17 | createdBy:{
18 | type: Schema.Types.ObjectId,
19 | ref : "user",
20 | },
21 | }, { timestamps : true}
22 | )
23 |
24 | const blog = model('blog',blogSchema);
25 |
26 | module.exports = blog;
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/models/comments.js:
--------------------------------------------------------------------------------
1 | const {Schema , model} = require('mongoose')
2 |
3 | const commentSchema = new Schema({
4 | content: {
5 | type: String,
6 | required : true,
7 | },
8 | blogId:{
9 | type: Schema.Types.ObjectId,
10 | ref:"blog"
11 | },
12 | createdBy:{
13 | type: Schema.Types.ObjectId,
14 | ref:"user",
15 | },
16 | }, {timestamps:true})
17 |
18 | const Comment = model("comment",commentSchema);
19 |
20 | module.exports = Comment;
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/models/user.js:
--------------------------------------------------------------------------------
1 | const {Schema,model}= require('mongoose');
2 | const { createHmac ,randomBytes } = require('node:crypto');
3 | const {createTokenForUser} = require('../services/authentication')
4 |
5 | const userSchema = new Schema(
6 | {
7 | fullName:{
8 | type:'String',
9 | required : true
10 | },
11 | email:{
12 | type:String,
13 | required:true,
14 | unique:true
15 | },
16 | salt:{
17 | type:String,
18 | }
19 | ,
20 | password:{
21 | type:String,
22 | requied:true
23 | },
24 | profileImageURL:{
25 | type:String,
26 | default:'/images/default.png',
27 | },
28 | role:{
29 | type:String,
30 | enum:["USER","ADMIN"],
31 | default:"USER",
32 | }
33 | },
34 | {timestamp: true}
35 | );
36 |
37 | //using pre middleware of mangoose
38 | userSchema.pre('save',function(){
39 | const user = this;
40 | if(!user.isModified("password")) return;
41 | const salt = randomBytes(16).toString(); //random string
42 | const hashedPassword = createHmac('sha256',salt)
43 | .update(user.password)
44 | .digest("hex");
45 | this.salt = salt;
46 | this.password=hashedPassword;
47 |
48 | })
49 |
50 | //making function
51 | userSchema.static('matchPasswordAndGenerateToken',async function(email,password){
52 | const user =await this.findOne({email});
53 | if(!user) throw new Error('User not found !');
54 |
55 | console.log(user);
56 | const salt = user.salt;
57 | const hashedPassword = user.password;
58 |
59 | const userProvideHash = createHmac("sha256",salt)
60 | .update(password)
61 | .digest("hex")
62 |
63 | if(hashedPassword !== userProvideHash){
64 | throw new Error("Incorrect Password!");
65 | }
66 | const token = createTokenForUser(user)
67 | return token;
68 | })
69 |
70 | const User = model('user',userSchema)
71 |
72 | module.exports= User;
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "29_setting_up_project-nodejs_blogging_app",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node app.js",
9 | "dev": "nodemon app.js"
10 | },
11 | "author": "",
12 | "license": "ISC",
13 | "dependencies": {
14 | "cookie-parser": "^1.4.6",
15 | "dotenv": "^16.4.5",
16 | "ejs": "^3.1.9",
17 | "express": "^4.19.2",
18 | "jsonwebtoken": "^9.0.2",
19 | "mongoose": "^8.3.0",
20 | "multer": "^1.4.5-lts.1",
21 | "nodemon": "^3.1.0"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/public/images/default.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/32_Deploy_NodeJS_App_on_Cloud/public/images/default.png
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712311193510-Screenshot (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712311193510-Screenshot (1).png
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712311768043-Screenshot (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712311768043-Screenshot (1).png
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712428496751-1_A7PQiIdB5buNa0mgq063Xg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712428496751-1_A7PQiIdB5buNa0mgq063Xg.png
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712429054876-piyu.avif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712429054876-piyu.avif
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712429113684-fire.avif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/32_Deploy_NodeJS_App_on_Cloud/public/uploads/1712429113684-fire.avif
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/routes/blog.js:
--------------------------------------------------------------------------------
1 | const {Router} = require('express')
2 | const multer = require('multer')
3 | const path = require('path')
4 | const router = Router();
5 | const Blog = require('../models/blog');
6 | const Comment = require('../models/comments');
7 |
8 | const storage = multer.diskStorage({
9 | destination: function (req, file, cb) {
10 | cb(null, path.resolve(`./public/uploads/`))
11 | },
12 | filename: function (req, file, cb) {
13 | const fileName = `${Date.now()}-${file.originalname}`
14 | cb(null,fileName);
15 | }
16 | })
17 | const upload = multer({ storage: storage })
18 |
19 | router.get('/add-new', (req, res)=>{
20 | return res.render('addBlog',{
21 | user: req.user,
22 | })
23 | })
24 |
25 | router.post('/', upload.single('coverImage'), async(req, res)=>{
26 | const {title , body} = req.body;
27 | const blog = await Blog.create({
28 | body,
29 | title,
30 | createdBy: req.user._id,
31 | coverImageURL: `/uploads/${req.file.filename}`
32 | })
33 | return res.redirect(`/blog/${blog._id}`)
34 | })
35 |
36 | router.get('/:id',async(req, res)=>{
37 | const blog = await Blog.findById(req.params.id).populate("createdBy");
38 | const comments = await Comment.find({blogId: req.params.id}).populate("createdBy")
39 | console.log("blog: ",blog)
40 | return res.render('blog',{
41 | user: req.user,
42 | blog,
43 | comments,
44 | })
45 | })
46 |
47 | router.post('/comment/:blogId',async(req,res)=>{
48 | await Comment.create({
49 | content: req.body.content,
50 | blogId: req.params.blogId,
51 | createdBy: req.user._id,
52 | })
53 | return res.redirect(`/blog/${req.params.blogId}`)
54 |
55 | })
56 | module.exports = router;
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/routes/user.js:
--------------------------------------------------------------------------------
1 | const {Router} = require('express');
2 | const User = require('../models/user')
3 | const router = Router();
4 |
5 | router.get('/signin',(req,res)=>{
6 | return res.render("signin")
7 | })
8 | router.get('/signup',(req,res)=>{
9 | return res.render("signup");
10 | })
11 | router.post('/signup',async (req,res)=>{
12 | const {fullName , password , email } = req.body;
13 | await User.create({
14 | fullName,
15 | email,
16 | password
17 | });
18 | return res.redirect('/');
19 | })
20 |
21 | router.post('/signin',async(req,res)=>{
22 | const { password , email } = req.body;
23 | try {
24 | const token =await User.matchPasswordAndGenerateToken(email,password);
25 | console.log("Token",token);
26 | return res.cookie('token',token).redirect('/');
27 | } catch (error) {
28 | return res.render('signin',{
29 | error:"Incorrect Email or Password",
30 | });
31 | }
32 |
33 |
34 | })
35 |
36 | router.get('/logout',(req, res)=>{
37 | res.clearCookie('token').redirect('/');
38 | })
39 | module.exports=router;
40 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/services/authentication.js:
--------------------------------------------------------------------------------
1 | const JWT = require('jsonwebtoken')
2 |
3 | const secret = "$uperMan@123";
4 |
5 | function createTokenForUser(user){
6 | const payload = {
7 | _id : user._id,
8 | email: user.email,
9 | profileImageURL : user.profileImageURL,
10 | role: user.role,
11 | fullName : user.fullName,
12 | };
13 | const token = JWT.sign(payload,secret);
14 | return token;
15 | }
16 |
17 | function validateToken(token){
18 | const payload = JWT.verify(token , secret);
19 | return payload;
20 | }
21 |
22 | module.exports ={
23 | createTokenForUser,
24 | validateToken
25 | }
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/addBlog.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Add New Blog Page
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 | Blog Title
14 |
15 |
16 |
17 | Cover Image
18 |
19 |
20 |
21 |
22 | Write Your Blog
23 |
24 |
25 | Button
26 |
27 |
28 |
29 | <%- include('./partials/scripts') %>
30 |
31 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/blog.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Homepage
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
<%= blog.title %>
12 |
13 |
<%= blog.body %>
14 |
15 |
16 |
17 |
18 | <%= blog.createdBy.fullName %>
19 |
20 |
21 |
Comments (<%= comments.length %>)
22 | <% if (locals.user) { %>
23 |
24 |
25 |
26 |
27 | Add
28 |
29 | <% } %>
30 |
31 | <% comments.forEach(comment => { %>
32 |
33 |
34 | <%= comment.createdBy.fullName %>
35 |
<%= comment.content %>
36 |
37 | <% }) %>
38 |
39 |
40 |
41 | <%- include('./partials/scripts') %>
42 |
43 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/home.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Homepage
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 | <% blogs.forEach(blog => { %>
12 |
13 |
14 |
15 |
16 |
<%= blog.title %>
17 |
View
18 |
19 |
20 |
21 |
22 |
23 | <% }) %>
24 |
25 |
26 | <%- include('./partials/scripts') %>
27 |
28 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/partials/head.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/partials/nav.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Blogify
4 |
5 |
6 |
7 |
8 |
9 |
10 | Home
11 |
12 | <% if (locals.user) { %>
13 |
14 | Add Blog
15 |
16 |
17 |
20 |
23 |
24 | <% }else { %>
25 |
26 | Create Account
27 |
28 |
29 |
30 |
31 | Signin
32 |
33 |
34 | <% } %>
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | <% if(locals.error){ %>
43 |
44 |
45 | <%= locals.error %>
46 |
47 |
48 |
49 | <% }
50 | %>
51 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/partials/scripts.ejs:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/signin.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signin
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 |
Email address
14 |
15 |
We'll never share your email with anyone else.
16 |
17 |
18 |
19 | Password
20 |
21 |
22 |
23 | Submit
24 |
25 |
26 | <%- include('./partials/scripts') %>
27 |
28 |
--------------------------------------------------------------------------------
/32_Deploy_NodeJS_App_on_Cloud/views/signup.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | <%- include('./partials/head') %>
5 | Signup
6 |
7 |
8 |
9 | <%- include('./partials/nav') %>
10 |
11 |
12 |
13 | Full Name
14 |
15 |
16 |
17 |
Email address
18 |
19 |
We'll never share your email with anyone else.
20 |
21 |
22 |
23 | Password
24 |
25 |
26 |
27 | Submit
28 |
29 |
30 | <%- include('./partials/scripts') %>
31 |
32 |
--------------------------------------------------------------------------------
/33_WebSocket/Readme.md:
--------------------------------------------------------------------------------
1 | # WebSocket
2 |
3 | - In general , We send request to the server , server responds to our request and request-response cycle will be closed.
4 | - Communication is single direction. Client request then Server responds (req-res cycle closed)
5 |
6 | - Problem :
7 | - Everytime when user request to the server there is message is available or not. (Chat App)
8 | - This is called `Polling`.
9 | - If message is not available then we are also reuesting to the server
10 | - Unneccesarly increasing the load to the server.
11 |
12 | - Solution :
13 | - Clinet sent `HTTP` request and tells , i want to make `WebSocket` connection.
14 | - `Upgrade` Header upgrades `http` connection to `websocket` connection.
15 | - any one can send message (server <--> Client) (Bidirectional).
16 | - You don't close the websocket connection unless you want.
17 | - WebSocket is just a `protocol`, provides `full-duplex` communication.
18 | - We don't need `Polling`.
19 |
20 |
21 | - We use `Socket.io` Library.
22 |
--------------------------------------------------------------------------------
/33_WebSocket/index.js:
--------------------------------------------------------------------------------
1 | const http = require('http')
2 | const express = require('express')
3 | const path = require('path')
4 | const {Server} = require("socket.io")
5 |
6 | const app = express();
7 | const server = http.createServer(app);
8 | const io = new Server(server);
9 |
10 | //Socket.io
11 | io.on('connection',(socket)=>{
12 | socket.on('user-message',(message)=>{
13 | io.emit("message",message);
14 | })
15 | console.log('A new user has connected',socket.id)
16 | })
17 |
18 | app.use(express.static(path.resolve('./public')));
19 |
20 | app.get('/',(req,res)=>{
21 | return res.sendFile("")
22 | })
23 | server.listen(9000, ()=>{
24 | console.log(`Server started at 9000`);
25 | })
--------------------------------------------------------------------------------
/33_WebSocket/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "33_websocket",
3 | "version": "1.0.0",
4 | "description": "- In general , We send request to the server , server responds to our request and request-response cycle will be closed.\r - Communication is single direction. Client request then Server responds (req-res cycle closed)",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "express": "^4.19.2",
13 | "socket.io": "^4.7.5"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/33_WebSocket/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Chat App
7 |
8 |
9 | Chatting
10 |
11 | Send
12 |
13 |
14 |
15 |
33 |
34 |
--------------------------------------------------------------------------------
/34_Streams/20M.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/34_Streams/20M.txt
--------------------------------------------------------------------------------
/34_Streams/Readme.md:
--------------------------------------------------------------------------------
1 | # Streams
2 |
3 | - Streams is used to send files in chunks.
4 | - To make memory efficient server
5 | - as data comes send to user in chunks.
6 |
--------------------------------------------------------------------------------
/34_Streams/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const fs = require("fs");
3 | const statusMonitor = require('express-status-monitor');
4 | const zlib = require('zlib')
5 |
6 | const app = express();
7 | const PORT = 8000;
8 | app.use(statusMonitor());
9 |
10 | // Stream Read (20M.txt) --> Zipper --> fs write stream
11 | fs.createReadStream("20M.txt").pipe(
12 | zlib.createGzip().pipe(fs.createWriteStream("20M.txt"))
13 | )
14 | app.get('/', (req, res) => {
15 | const stream = fs.createReadStream("20M.txt","utf-8");
16 | stream.on('data', (chunk)=>{
17 | res.write(chunk);
18 | stream.on("end" , () => res.end());
19 | })
20 | });
21 |
22 | app.listen(PORT, () => {
23 | console.log(`Server started at http://localhost:${PORT}`);
24 | });
25 |
--------------------------------------------------------------------------------
/34_Streams/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "express": "^4.19.2",
4 | "express-status-monitor": "^1.3.4"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/35_Scale_NodeJS_App_using_Cluster_module/Readme.md:
--------------------------------------------------------------------------------
1 | # Scale NodeJS application using the cluster module
2 |
3 | - Multiple users concurrently accesing the server then Workload increases.
4 | - When users increases then we can use clusters.
5 | - We distribute the workload on server into multiple apllication threads of nodejs.
6 | - We can make worker threads as no of cpus.
7 | - When we use cluster it divides assigns the diifferent work with diffirent threads in nodejs in round robin fashion to distribute the workload.
--------------------------------------------------------------------------------
/35_Scale_NodeJS_App_using_Cluster_module/app.js:
--------------------------------------------------------------------------------
1 | const express = require("express")
2 |
3 | const app = express()
4 | const PORT = 8000;
5 |
6 | app.get("/",(req , res)=>{
7 | return res.json({message: `Hello from Express Server ${process.pid} 🚀`})
8 |
9 | })
10 |
11 | app.listen(PORT, ()=> console.log(`Server Started at PORT: ${PORT}`))
12 |
--------------------------------------------------------------------------------
/35_Scale_NodeJS_App_using_Cluster_module/cluster.js:
--------------------------------------------------------------------------------
1 | const cluster = require('node:cluster')
2 | const os = require('os')
3 | const express = require('express')
4 |
5 | const totalCPUs = os.cpus().length;
6 |
7 | // console.log(totalCPUs)
8 |
9 | if(cluster.isPrimary){
10 |
11 | // Fork workers.
12 | for (let i = 0; i < totalCPUs; i++) {
13 | cluster.fork();
14 | }
15 | }
16 | else{
17 | const app = express();
18 | const PORT = 8000;
19 |
20 | app.get("/",(req , res)=>{
21 | return res.json({message: `Hello from Express Server ${process.pid} 🚀`})
22 |
23 | })
24 | app.listen(PORT, ()=> console.log(`Server Started at PORT: ${PORT}`))
25 |
26 | }
--------------------------------------------------------------------------------
/35_Scale_NodeJS_App_using_Cluster_module/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "35_scale_nodejs_app_using_cluster_module",
3 | "version": "1.0.0",
4 | "description": "- Multiple users concurrently accesing the server then Workload increases.\r - When users increases then we can use clusters.\r - We distribute the workload on server into multiple apllication threads of nodejs.",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "express": "^4.19.2"
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/36_What_is_Nginx/Readme.md:
--------------------------------------------------------------------------------
1 | # What is Nginx (Engine-X)?
2 |
3 | - NGINX is a powerful web server and uses a non-threaded , event-driven architecture.
4 |
5 | - It can also do other important things ,such as `load balancing` , and `HTTP caching`, or be used as a `reverse proxy`.
6 |
7 | - Forward Proxy
8 | - When multiple clients connecting to VPN Sever. And VPN sever is connecting to a server.
9 | - Only one client for server i.e. VPN.
10 |
11 | - Reverse Proxy:
12 | - When a clinet is connecting a VPN server and that vpn is connecting to multiple servers.
13 | - Users don't know request will be serve to which server.
14 |
15 | - Reverse Proxy:
16 | - Nginx decides your request will be serve to which server.
17 | - Load Balance - distribute the load.
18 | - Http Cache - make cache to reduce req-res cycle.
19 |
20 | - Advantage:
21 | - Can handle 10000 concurrent requests
22 | - Cache HTTP requests
23 | - Act as Reverse Proxy
24 | - Act as Load Balancer
25 | - Act as an API Gateway
26 | - Serve and Cache Static files like images, Videos, etc
27 | - Handle SSL Certificates
28 |
29 | - Prerequisite
30 | - Docker , Basic Linux Commands , Containerization
--------------------------------------------------------------------------------
/37_Install_&_Setup_Nginx/Readme.md:
--------------------------------------------------------------------------------
1 | #
2 |
3 | - By deafult Nginx runs on PORT 80.
4 | - Insta Nginx - ``
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "client",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@apollo/client": "^3.9.11",
7 | "@testing-library/jest-dom": "^5.17.0",
8 | "@testing-library/react": "^13.4.0",
9 | "@testing-library/user-event": "^13.5.0",
10 | "graphql": "^16.8.1",
11 | "react": "^18.2.0",
12 | "react-dom": "^18.2.0",
13 | "react-scripts": "5.0.1",
14 | "web-vitals": "^2.1.4"
15 | },
16 | "scripts": {
17 | "start": "react-scripts start",
18 | "build": "react-scripts build",
19 | "test": "react-scripts test",
20 | "eject": "react-scripts eject"
21 | },
22 | "eslintConfig": {
23 | "extends": [
24 | "react-app",
25 | "react-app/jest"
26 | ]
27 | },
28 | "browserslist": {
29 | "production": [
30 | ">0.2%",
31 | "not dead",
32 | "not op_mini all"
33 | ],
34 | "development": [
35 | "last 1 chrome version",
36 | "last 1 firefox version",
37 | "last 1 safari version"
38 | ]
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/42_GraphQL_NodeJS/client/public/favicon.ico
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 | You need to enable JavaScript to run this app.
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/42_GraphQL_NodeJS/client/public/logo192.png
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/42_GraphQL_NodeJS/client/public/logo512.png
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/src/App.js:
--------------------------------------------------------------------------------
1 |
2 |
3 | import { useQuery ,gql} from '@apollo/client';
4 | const query = gql`
5 | query GetTodosWithUser {
6 | getTodos{
7 | id
8 | title
9 | completed
10 | user{
11 | id
12 | name
13 | }
14 | }
15 | }
16 | `
17 |
18 |
19 | function App() {
20 |
21 | const {data, loading} = useQuery(query)
22 |
23 | if(loading) return Loading ...
24 | return (
25 |
26 |
27 |
28 | {data.getTodos.map(todo => (
29 |
30 | {todo.title}
31 | {todo.user.name}
32 |
33 |
34 | ))}
35 |
36 |
37 |
38 | );
39 | }
40 |
41 | export default App;
42 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/src/App.test.js:
--------------------------------------------------------------------------------
1 | import { render, screen } from '@testing-library/react';
2 | import App from './App';
3 |
4 | test('renders learn react link', () => {
5 | render( );
6 | const linkElement = screen.getByText(/learn react/i);
7 | expect(linkElement).toBeInTheDocument();
8 | });
9 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom/client';
3 | import './index.css';
4 | import App from './App';
5 | import reportWebVitals from './reportWebVitals';
6 |
7 | import {ApolloClient, InMemoryCache , ApolloProvider} from '@apollo/client'
8 | const client = new ApolloClient({
9 | uri: 'http://localhost:8000/graphql',
10 | cache: new InMemoryCache()
11 | })
12 |
13 | const root = ReactDOM.createRoot(document.getElementById('root'));
14 | root.render(
15 |
16 |
17 |
18 |
19 |
20 | );
21 |
22 | // If you want to start measuring performance in your app, pass a function
23 | // to log results (for example: reportWebVitals(console.log))
24 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
25 | reportWebVitals();
26 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/client/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom';
6 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/server/index.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const { ApolloServer } = require("@apollo/server");
3 | const { expressMiddleware } = require("@apollo/server/express4");
4 | const bodyParser = require("body-parser");
5 | const cors = require("cors");
6 | const { default: axios } = require("axios");
7 |
8 | async function startServer() {
9 | const app = express();
10 | const server = new ApolloServer({
11 | typeDefs: `
12 | type User {
13 | id: ID!
14 | name: String!
15 | username: String!
16 | email: String!
17 | phone: String!
18 | website: String!
19 | }
20 | type Todo {
21 | id: ID!
22 | title : String!
23 | completed: Boolean
24 | user: User
25 | },
26 |
27 | type Query {
28 | getTodos: [Todo]
29 | getAllUsers: [User]
30 | getUser(id: ID!): User
31 | }
32 |
33 | `,
34 | resolvers: {
35 | Todo: {
36 | user: async(todo) => (await axios.get(`https://jsonplaceholder.typicode.com/users/${todo.userId}`)).data
37 | },
38 | Query: {
39 | getTodos: async () =>{
40 | return (await axios.get("https://jsonplaceholder.typicode.com/todos")).data;
41 | },
42 | getAllUsers: async () => {
43 | return (await axios.get("https://jsonplaceholder.typicode.com/users")).data;
44 | },
45 | getUser: async (_, { id }) => {
46 | return (await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`)).data;
47 | },
48 | },
49 | },
50 | });
51 |
52 | app.use(bodyParser.json());
53 | app.use(cors());
54 |
55 | await server.start();
56 |
57 | app.use("/graphql", expressMiddleware(server));
58 |
59 | app.listen(8000, () => console.log("Serevr Started at PORT 8000"));
60 | }
61 |
62 | startServer();
63 |
--------------------------------------------------------------------------------
/42_GraphQL_NodeJS/server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "author": "",
10 | "license": "ISC",
11 | "dependencies": {
12 | "@apollo/server": "^4.10.4",
13 | "@types/axios": "^0.14.0",
14 | "axios": "^1.6.8",
15 | "body-parser": "^1.20.2",
16 | "cors": "^2.8.5",
17 | "express": "^4.19.2",
18 | "graphql": "^16.8.1"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/43_Threads_App_GraphQL_Clone/Readme.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/unstoppableayush/Backend-NodeJS/1697f51cfce12404dee1153952f53eb2bb1e97d4/43_Threads_App_GraphQL_Clone/Readme.md
--------------------------------------------------------------------------------