Skip to content

Commit

Permalink
Merge pull request #49 from AbdulAziz0682/backendDevelopment
Browse files Browse the repository at this point in the history
Added Basic CRUD Api in NodeJS
  • Loading branch information
iamzaidsoomro authored Oct 23, 2021
2 parents 6aed409 + b52a5d2 commit 9cf07fd
Show file tree
Hide file tree
Showing 5 changed files with 616 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/node_modules/
159 changes: 159 additions & 0 deletions Backend Development/CRUD Api/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Rest API in NodeJS</title>
<style>
body {
display: flex;
justify-content: center;
align-items: flex-start;
padding-top: 30px;
padding-bottom: 30px;
}
#root {
display: flex;
flex-direction: column;
gap: 10px;
width: 50%;
min-width: 300px;
border: 3px solid gray;
border-radius: 8px;
padding: 3px;
}
h1 {
text-align: center;
}
</style>
</head>
<body>
<div id="root">
<h1>Basic Rest API in NodeJS</h1>
<div id="getBooks" style="display:flex; flex-direction: column; width: 100%">
<pre id="books"></pre>
<button type="button" onclick="getBooks()">Get Books</button>
</div>
<div id="getBook" style="display:flex; flex-direction: column; width: 100%">
<pre id="book"></pre>
<div style="display: flex; gap: 8px; width: 100%;">
<input id="bookID" type="number" placeholder="Book id" style="flex-grow: 1;" />
<button type="button" onclick="getBook()" style="flex-grow: 1;">Get Book</button>
</div>
</div>
<div id="addBook" style="display:flex; flex-direction: column; width: 100%; gap: 3px">
<div style="display: flex; gap: 8px; width: 100%;">
<label for="name" style="width: 25%; min-width: fit-content;">Name:</label>
<input id="name" name="name" type="text" placeholder="Book name" style="flex-grow: 1;" />
</div>
<div style="display: flex; gap: 8px; width: 100%;">
<label for="author" style="width: 25%; min-width: fit-content;">Author:</label>
<input id="author" name="author" type="text" placeholder="Book author" style="flex-grow: 1;" />
</div>
<div style="display: flex; gap: 8px; width: 100%;">
<label for="edition" style="width: 25%; min-width: fit-content;">Edition:</label>
<input id="edition" name="edition" type="text" placeholder="Book edition" style="flex-grow: 1;" />
</div>
<div style="display: flex; gap: 8px; width: 100%;">
<label for="price" style="width: 25%; min-width: fit-content;">Price:</label>
<input id="price" name="price" type="number" placeholder="Book price (USD)" style="flex-grow: 1;" />
</div>
<button type="button" onclick="addBook()">Add Book</button>
</div>
<div id="updateBook" style="display:flex; flex-direction: column; width: 100%; gap: 3px">
<div style="display: flex; gap: 8px; width: 100%;">
<label for="bookID" style="width: 25%; min-width: fit-content;">bookID:</label>
<input id="newbookID" name="id" type="text" placeholder="Book ID" style="flex-grow: 1;" />
</div>
<div style="display: flex; gap: 8px; width: 100%;">
<label for="name" style="width: 25%; min-width: fit-content;">Name:</label>
<input id="newname" name="name" type="text" placeholder="Book name" style="flex-grow: 1;" />
</div>
<div style="display: flex; gap: 8px; width: 100%;">
<label for="author" style="width: 25%; min-width: fit-content;">Author:</label>
<input id="newauthor" name="author" type="text" placeholder="Book author" style="flex-grow: 1;" />
</div>
<div style="display: flex; gap: 8px; width: 100%;">
<label for="edition" style="width: 25%; min-width: fit-content;">Edition:</label>
<input id="newedition" name="edition" type="text" placeholder="Book edition" style="flex-grow: 1;" />
</div>
<div style="display: flex; gap: 8px; width: 100%;">
<label for="price" style="width: 25%; min-width: fit-content;">Price:</label>
<input id="newprice" name="price" type="number" placeholder="Book price (USD)" style="flex-grow: 1;" />
</div>
<button type="button" onclick="updateBook()">Update Book</button>
</div>
<div id="deleteBook" style="display:flex; flex-direction: column; width: 100%">
<div style="display: flex; gap: 8px; width: 100%;">
<input id="deletebookID" type="number" placeholder="Book id" style="flex-grow: 1;" />
<button type="button" onclick="deleteBook()" style="flex-grow: 1;">Delete Book</button>
</div>
</div>
</div>
<script>
function getBooks(){
fetch('/books')
.then(response => response.json())
.then(data => {
let text = JSON.stringify(data, null, 2);
document.getElementById('books').innerText = text;
});
}
function getBook(){
const bookID = document.getElementById('bookID').value;
fetch('/books/'+bookID) // /books/1 matches /books/:id route on backend
.then(response => response.json())
.then(data => {
let text = JSON.stringify(data, null, 2);
document.getElementById('book').innerText = text;
});
}
function addBook(){
const name = document.getElementById('name').value;
const author = document.getElementById('author').value;
const edition = document.getElementById('edition').value;
const price = document.getElementById('price').value;
const book = {
name: name,
author: author,
edition: edition,
price: price,
};
fetch('/books', {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(book)
}).then(response => alert('Book added successfully')).catch(() => alert('Couldnt add book'));
}
function updateBook(){
const id = document.getElementById('newbookID').value;
const name = document.getElementById('newname').value;
const author = document.getElementById('newauthor').value;
const edition = document.getElementById('newedition').value;
const price = document.getElementById('newprice').value;
fetch('/books', {
method: 'PUT', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: id,
name: name,
author: author,
edition: edition,
price: price,
})
}).then(response => alert('Book updated successfully')).catch(() => alert('Couldnt update book'));
}
function deleteBook(){
const id = document.getElementById('deletebookID').value;
fetch('/books/'+id, {
method: 'DELETE', // *GET, POST, PUT, DELETE, etc.
}).then(response => alert('Book deleted successfully')).catch(() => alert('Couldnt delete book'));
}
</script>
</body>
</html>
62 changes: 62 additions & 0 deletions Backend Development/CRUD Api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// To run this nodejs app, install all dependencies by typing 'npm install' in root directory i.e. CRUD Api
const express = require('express'); // Express is a javascript library for nodejs. It is used for backend development.
const path = require('path');

const server = express(); // Creating express server

// The form data will be sent in POST request body
// To extract it, we need to use urlencoded() with express as a 'middleware'
//server.use(express.urlencoded({extended: true}));
server.use(express.json());

server.listen(/* port */ 3000, /* callback */ () => {
console.log('listening on port 3000... navigate to http://localhost:3000/');
});

let books = [
{id: 1, name: 'Eloquent Javascript', author: 'Marijn Haverbeke', edition: '3rd', price: '5' /* USD */},
{id: 2, name: 'Effective Java', author: 'Joshua Bloch', edition: '1st', price: '3' /* USD */},
{id: 3, name: 'Python Workout', author: 'Reuven M. Lerner', edition: '1st', price: '10' /* USD */},
]

server.get(/* route */ '/books', /* callback */ (req, res) => { // Callback can be arrow function or ES5 function
res.json(books); // json() method sends the data in json format
}); // get() method is used for when a get request is made on a route, here '/books' is the route

server.get('/books/:id', (req, res) => {
// :id in route name represents request parameters
let id = req.params.id; // You can access id (request parameter) in 'req.params' object
id = Number(id); // The id is converted from string to number
const book = books.find((b) => b.id === id);
res.json(book);
});

server.delete('/books/:id', (req, res) => {
let id = req.params.id;
id = Number(id);
books = books.filter((b) => b.id !== id);
res.end()
});

server.post('/books', (req, res) => {
// In every post, there's data in req.body object
const book = req.body;
let newID = books[books.length-1].id + 1; // Always 1 greater than the latest book
book.id = newID;
books.push(book);
res.end();
});

server.put('/books', (req, res) => {
const book = req.body;
const index = books.findIndex((b) => b.id == book.id); // Finding the book index
// return console.log(books[index]);
books[index] = book; // Replacing the existing book with new book
res.end();
});

server.get('/', (req, res) => {
// home route
const html = path.resolve('./index.html'); // Converts the relative path to absolute path
res.sendFile(html); // sendFile method is used to send different types of files like html, img, json in response
});
Loading

0 comments on commit 9cf07fd

Please sign in to comment.