jkwjdhbwdbkj
unknown
javascript
2 years ago
9.7 kB
11
Indexable
//products.json
[
{
"id": "1",
"name": "Airpods Wireless Bluetooth Headphones",
"description": "Bluetooth technology lets you connect it with compatible devices wirelessly High-quality AAC audio offers immersive listening experience Built-in microphone allows you to take calls while working",
"price": 89.99
},
{
"id": "2",
"name": "iPhone 11 Pro 256GB Memory",
"description": "Introducing the iPhone 11 Pro. A transformative triple-camera system that adds tons of capability without complexity. An unprecedented leap in battery life",
"price": 599.99
},
{
"id": "3",
"name": "Cannon EOS 80D DSLR Camera",
"description": "Characterized by versatile imaging specs, the Canon EOS 80D further clarifies itself using a pair of robust focusing systems and an intuitive design",
"price": 929.99
},
{
"id": "4",
"name": "Sony Playstation 4 Pro White Version",
"description": "The ultimate home entertainment center starts with PlayStation. Whether you are into gaming, HD movies, television, music",
"price": 399.99
},
{
"id": "5",
"name": "Logitech G-Series Gaming Mouse",
"description": "Get a better handle on your games with this Logitech LIGHTSYNC gaming mouse. The six programmable buttons allow customization for a smooth playing experience",
"price": 49.99
}
]
//utils.js
const fs = require('fs');
function writeDataToFile(filename, content) {
fs.writeFileSync(filename, JSON.stringify(content), 'utf-8', (err) => {
if (err) {
console.log(err);
}
})
}
function getPostData(req) {
return new Promise((resolve, reject) => {
try {
let body = "";
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
resolve(body);
})
} catch (error) {
reject(error);
}
})
}
module.exports = {
writeDataToFile,
getPostData
};
//productController.js
// const { writeHeapSnapshot } = require("v8");
const Product = require("./productModel");
const { getPostData } = require('./utils.js');
//Desc: Gets All Products
//Route: GET /api/products
async function getProducts(req, res) {
try {
const products = await Product.findAll();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(products)) //array of js objs from .json file should be converted to string (in express it does auto convertion)
}
catch (error) {
console.log(error);
}
}
//Desc: Gets Single Products
//Route: GET /api/products/:id
async function getProduct(req, res, id) {
try {
const product = await Product.findById(id);
if (!product) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: "Product Not Found" }));
}
else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(product)) //array of js objs from .json file should be converted to string (in express it does auto convertion)
}
}
catch (error) {
console.log(error);
}
}
//Desc: Create a Product
//Route: POST /api/products/:id
async function createProduct(req, res) {
try {
// const product = {
// title: "Test Product",
// description: "This is my product",
// price: 100
// }
// res.writeHead(201, { "Content-Type": 'application/json' });
// const newProduct = await Product.createdProduct(product);
// return res.end(JSON.stringify(newProduct));
// let body = "";
// req.on('data', (chunk) => {
// body += chunk.toString();
// })
// req.on('end', async () => {
// const { title, description, price } = JSON.parse(body);
// const product = { title, description, price };
// const newProduct = await Product.createdProduct(product);
// res.writeHead(201, { "Content-Type": 'application/json' });
// return res.end(JSON.stringify(newProduct));
// });
const body = await getPostData(req);
const { title, description, price } = JSON.parse(body);
const product = { title, description, price };
const newProduct = await Product.createdProduct(product);
res.writeHead(201, { "Content-Type": 'application/json' });
return res.end(JSON.stringify(newProduct));
}
catch (error) {
console.log(error);
}
}
//Desc: Update a Product
//Route: PUT /api/products/:id
async function updateProduct(req, res, id) {
try {
const product = await Product.findById(id);
if (!product) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: "Product Not Found" }));
}
else {
const body = await getPostData(req);
const { title, description, price } = JSON.parse(body);
const productData = {
title: title || product.title,
description: description || product.description,
price: price || product.price
};
const updProduct = await Product.update(productData);
res.writeHead(200, { "Content-Type": 'application/json' });
return res.end(JSON.stringify(updProduct));
}
}
catch (error) {
console.log(error);
}
}
//Desc: Delete Products
//Route: DELETE /api/products/:id
async function deleteProduct(req, res, id) {
try {
const product = await Product.findById(id);
if (!product) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: "Product Not Found" }));
}
else {
await Product.remove(id);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: `Product ${id} removed` })); //array of js objs from .json file should be converted to string (in express it does auto convertion)
}
}
catch (error) {
console.log(error);
}
}
module.exports = {
getProducts,
getProduct,
createProduct,
updateProduct,
deleteProduct
};
//productModel.js
// const { create } = require('domain');
const products = require('./products.json');
const { v4: uuidv4 } = require('uuid');
const { writeDataToFile } = require('./utils.js');
function findAll() {
return new Promise((resolve, reject) => {
resolve(products);
})
}
function findById(id) {
return new Promise((resolve, reject) => {
const product = products.find((p) => p.id === id);
resolve(product);
})
}
function createdProduct(product) {
return new Promise((resolve, reject) => {
const newProduct = { id: uuidv4(), ...product };
products.push(newProduct);
writeDataToFile('./products.json', products);
resolve(newProduct);
})
}
function update(id, product) {
return new Promise((resolve, reject) => {
const index = products.findIndex((p) => p.id === id);
products[index] = { id, ...products };
writeDataToFile('./products.json', products);
resolve(products[index]);
})
}
function remove(id) {
return new Promise((resolve, reject) => {
products = products.filter((p) => p.id !== id);
writeDataToFile('./products.json', products);
resolve();
})
}
module.exports = {
findAll,
findById,
createdProduct,
update,
remove
};
//server.js
//This code links to products.json file for Rest API without using routes from express
const http = require('http');
const { getProducts, getProduct, createProduct, updateProduct, deleteProduct } = require('./productController');
// const { createdProduct } = require('./productModel');
const port = process.env.PORT || 5000;
const server = http.createServer((req, res) => {
// res.writeHead(200, { 'Content-Type': 'text/html' });
// res.write("Hello");
// res.end(); //Without url specification using conditional statements this code will execute without any error
if (req.url === '/api/products' && req.method === "GET") { //req.method makes the postman to execute this code when GET is present not POST, DELETE, PATCH
getProducts(req, res);
}
else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === "GET") {
let id = req.url.split('/')[3]; // Link: /api/products/1 =["","api","products","1"]
getProduct(req, res, id);
}
else if (req.url === "/api/products" && req.method === "POST") {
createProduct(req, res);
}
else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === "PUT") {
let id = req.url.split('/')[3]; // Link: /api/products/1 =["","api","products","1"]
updateProduct(req, res, id);
} else if (req.url.match(/\/api\/products\/([0-9]+)/) && req.method === "DELETE") {
let id = req.url.split('/')[3]; // Link: /api/products/1 =["","api","products","1"]
removeProduct(req, res, id);
}
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: "Route Not Found" }));
}
});
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
})
Editor is loading...
Leave a Comment