Skip to content

Commit

Permalink
commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mces58 authored Oct 7, 2023
1 parent c6e8db0 commit 751ded9
Show file tree
Hide file tree
Showing 46 changed files with 2,335 additions and 0 deletions.
45 changes: 45 additions & 0 deletions 12-error-handling-logging/06-uncaught-exception/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const express = require("express");
const app = express();
const productRouter = require("./router/product");
const categoryRouter = require("./router/category");
const userRouter = require("./router/user");
const mongoose = require("mongoose");
const error = require("./middleware/error");
const logger = require("./middleware/logger");
require("express-async-errors");
const config = require("config");

app.use(express.json());

app.get("/", (req, res) => {
res.send("Hello world");
});

app.use("/api/products", productRouter);
app.use("/api/categories", categoryRouter);
app.use("/api/users", userRouter);
app.use(error);

// throw new Error("Something failed during startup");
const p = Promise.reject(new Error("Something failed miserably!")); // hata yakalama işlemlerini yapıyoruz

(async () => {
const db = config.get("db.name");
const user = config.get("db.username");
const password = config.get("db.password");

await mongoose.connect(
`mongodb+srv://${user}:${password}@cluster0.el1u7yk.mongodb.net/${db}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);

logger.info("Connected to MongoDB...");
})();

const port = process.env.PORT || 3000;
app.listen(port, () => {
logger.info(`Listening on port ${port}`);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"db": {
"password": "DB_PASSWORD"
},
"auth": {
"jwtPrivateKey": "JWT_PRIVATE_KEY"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "shopapp web app",
"version": "1.0.0",
"description": "shopapp web app",
"main": "app.js"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "shopapp web api development",
"db": {
"name": "shopdb",
"username": "can"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "shopapp web api production",
"db": {
"name": "shopdb",
"username": "can"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const { Category, validateCategory } = require("../model/category");

exports.getAllCategories = async (req, res) => {
try {
const categories = await Category.find().populate(
"products",
"name price -_id"
);
res.send(categories);
} catch (error) {
res.status(500).send(error.message);
}
};

exports.getCategoryById = async (req, res) => {
const id = req.params.id;

try {
const category = await Category.findById(id);

if (!category) {
return res.status(404).send("Category not found");
}

res.send(category);
} catch (error) {
res.status(500).send(error.message);
}
};

exports.createCategory = async (req, res) => {
const validationResult = validateCategory(req.body);

if (validationResult.error) {
return res.status(400).send(validationResult.error.details[0].message);
}

const category = new Category({
name: req.body.name,
description: req.body.description,
products: req.body.products,
});

try {
await category.save();
res.send(category);
} catch (error) {
res.status(500).send(error.message);
}
};

exports.updateCategory = async (req, res) => {
const id = req.params.id;
try {
const category = await Category.findById(id);

if (!category) {
return res.status(404).send("Category not found");
}

const validationResult = validateCategory(req.body);

if (validationResult.error) {
return res.status(400).send(validationResult.error.details[0].message);
}

const { name, description } = req.body;

category.set({
name,
description,
});

const updatedCategory = await category.save();

res.send(updatedCategory);
} catch (error) {
res.status(500).send(error.message);
}
};

exports.deleteCategory = async (req, res) => {
const id = req.params.id;

try {
const category = await Category.findByIdAndDelete(id);

if (!category) {
return res.status(404).send("Category not found");
}

res.send(category);
} catch (error) {
res.status(500).send(error.message);
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const { Product, validateProduct } = require("../model/product");
require("express-async-errors");

module.exports.getAllProducts = async (req, res, next) => {
throw new Error("Could not get the products."); // hata fırlatıyoruz
const products = await Product.find().populate("category", "name");
res.send(products);
};

module.exports.getProductById = async (req, res) => {
const id = req.params.id;

const product = await Product.findOne({ _id: id }).select("name price");

if (!product) {
return res.status(404).send("Product not found");
}

res.send(product);
};

module.exports.createProduct = async (req, res) => {
const validationResult = validateProduct(req.body);

if (validationResult.error) {
return res.status(400).send(validationResult.error.details[0].message);
}

const product = new Product({
name: req.body.name,
price: req.body.price,
description: req.body.description,
image: req.body.image,
isActive: req.body.isActive,
category: req.body.category,
});

await product.save();
res.send(product);
};

module.exports.updateProduct = async (req, res) => {
const id = req.params.id;
const product = await Product.findById(id);

if (!product) {
return res.status(404).send("Product not found");
}

const validationResult = validateProduct(req.body);

if (validationResult.error) {
return res.status(400).send(validationResult.error.details[0].message);
}

const { name, price, description, image, isActive } = req.body;

product.set({
name,
price,
description,
image,
isActive,
});

const updatedProduct = await product.save();

res.send(updatedProduct);
};

module.exports.deleteProduct = async (req, res) => {
const id = req.params.id;

const product = await Product.findByIdAndDelete(id);

if (!product) {
return res.status(404).send("Product not found");
}

res.send(product);
};
74 changes: 74 additions & 0 deletions 12-error-handling-logging/06-uncaught-exception/controller/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const { User, validateRegister, validateLogin } = require("../model/user");
const bcrypt = require("bcrypt");

exports.getAllUsers = async (req, res) => {
try {
const users = await User.find();
res.send(users);
} catch (error) {
res.status(500).send(error.message);
}
};

exports.createUser = async (req, res) => {
const validationResult = validateRegister(req.body);

if (validationResult.error) {
return res.status(400).send(validationResult.error.details[0].message);
}

try {
const user = await User.findOne({ email: req.body.email });

if (user) {
return res.status(400).send("User already registered");
}

const hashedPassword = await bcrypt.hash(req.body.password, 10);

const newUser = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword,
});

await newUser.save();

const token = newUser.generateAuthToken();

res.header("x-auth-token", token).send(newUser);
} catch (error) {
res.status(500).send(error.message);
}
};

exports.authUser = async (req, res) => {
const validationResult = validateLogin(req.body);

if (validationResult.error) {
return res.status(400).send(validationResult.error.details[0].message);
}

try {
const user = await User.findOne({ email: req.body.email });

if (!user) {
return res.status(400).send("Invalid email or password");
}

const validPassword = await bcrypt.compare(
req.body.password,
user.password
);

if (!validPassword) {
return res.status(400).send("Invalid email or password");
}

const token = user.generateAuthToken();

res.header("x-auth-token", token).send("Logged in successfully");
} catch (error) {
res.status(500).send(error.message);
}
};
25 changes: 25 additions & 0 deletions 12-error-handling-logging/06-uncaught-exception/log/logfile.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
message: 'Listening on port 7070',
level: 'info',
timestamp: '2023-08-31 09:48:13'
}
{
message: 'Connected to MongoDB...',
level: 'info',
timestamp: '2023-08-31 09:48:15'
}
{
message: '500 - Could not get the products. - /api/products/ - GET - ::1',
level: 'error',
timestamp: '2023-08-31 09:48:21'
}
{
message: 'Listening on port 7070',
level: 'info',
timestamp: '2023-08-31 09:48:36'
}
{
message: 'Listening on port 7070',
level: 'info',
timestamp: '2023-08-31 09:49:02'
}
Loading

0 comments on commit 751ded9

Please sign in to comment.