Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .env
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
PORT=5002
TOKEN_ACCESS_SECRET=
DB_NAME=
DB_USER=
DB_PASSWORD=
DB_HOST=
TOKEN_ACCESS_SECRET=987654321
DB_NAME= "recipiesMysql.sql"
DB_USER= "Ernesto"
DB_PASSWORD="ElSalvador"
DB_HOST="Hostinger"
22 changes: 17 additions & 5 deletions config/db.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config ();

// Create a connection pool
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
Expand All @@ -10,19 +14,27 @@ const pool = mysql.createPool({

console.log('MySQL Pool created successfully');

// Create query
// Query function
const query = async (sql, values) => {
const connection = await pool.getConnection();
let connection;
try {
// Get a connection from the pool
connection = await pool.getConnection();

// Execute the query with provided SQL and values
const [results] = await connection.query(sql, values);

// Return the query results
return results;
} catch (err) {
return err;
console.error('Database query error:', err.message);
throw err; // Rethrow the error to be handled by the caller
} finally {
if (connection) {
connection.release();
// Release the connection back to the pool
await connection.release();
}
}
};

export default query;
export default connection;
83 changes: 77 additions & 6 deletions controllers/recipe.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,82 @@
import query from '../config/db.js';
import connection from '../config/db.js';


// controllers/recipeController.js

//import connection from '../config/db.js';

const recipeControllers = {
getAllRecipes: async (req, res) => {},
getOneRecipe: async (req, res) => {},
postRecipe: async (req, res) => {},
updateRecipe: async (req, res) => {},
deleteRecipe: async (req, res) => {},
getAllRecipes: async (req, res) => {
try {
const [rows] = connection.query('SELECT * FROM recipes');
res.status(200).json(rows);
} catch (error) {
res.status(500).json({ message: 'Error fetching recipes' });
}
},

getOneRecipe: async (req, res) => {
const { id } = req.params;
try {
const [rows] = await connection.query('SELECT * FROM recipes WHERE id = ?', [id]);
if (rows.length === 0) {
return res.status(404).json({ message: 'Recipe not found' });
}
res.status(200).json(rows[0]);
} catch (error) {
res.status(500).json({ message: 'Error fetching recipe' });
}
},

postRecipe: async (req, res) => {
const { title, description } = req.body;
const userId = req.userId;

try {
await connection.query(
'INSERT INTO recipes (title, description, user_id) VALUES (?, ?, ?)',
[title, description, userId]
);
res.status(201).json({ message: 'Recipe created successfully' });
} catch (error) {
res.status(500).json({ message: 'Error creating recipe' });
}
},

updateRecipe: async (req, res) => {
const { id } = req.params;
const { title, description } = req.body;
const userId = req.userId;

try {
const [result] = await connection.query(
'UPDATE recipes SET title = ?, description = ? WHERE id = ? AND user_id = ?',
[title, description, id, userId]
);

if (result.affectedRows === 0) {
return res.status(404).json({ message: 'Recipe not found or unauthorized' });
}
res.status(200).json({ message: 'Recipe updated successfully' });
} catch (error) {
res.status(500).json({ message: 'Error updating recipe' });
}
},

deleteRecipe: async (req, res) => {
const { id } = req.params;
const userId = req.userId;

try {
const [result] = await connection.query('DELETE FROM recipes WHERE id = ? AND user_id = ?', [id, userId]);
if (result.affectedRows === 0) {
return res.status(404).json({ message: 'Recipe not found or unauthorized' });
}
res.status(200).json({ message: 'Recipe deleted successfully' });
} catch (error) {
res.status(500).json({ message: 'Error deleting recipe' });
}
},
};

export default recipeControllers;
68 changes: 64 additions & 4 deletions controllers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,74 @@ import validateEmail from '../utils/validateEmail.js';
import validatePassword from '../utils/validatePassword.js';
import matchPasswords from '../utils/matchPasswords.js';
import hashPassword from '../utils/hashPassword.js';
import query from '../config/db.js';
import connection from '../config/db.js';


const userControllers = {
register: async (req, res) => {},
register: async (req, res) => {
const { name, email, password, confirmPassword } = req.body;

if (!validateEmail(email)) {
return res.status(400).json({ message: 'Invalid email format' });
}

if (!validatePassword(password)) {
return res.status(400).json({ message: 'Invalid password format' });
}

if (!matchPasswords(password, confirmPassword)) {
return res.status(400).json({ message: 'Passwords do not match' });
}

const hashedPassword = hashPassword(password);

try {
await connection.query(
'INSERT INTO users2 (name, email, password) VALUES (?, ?, ?)',
[name, email, hashedPassword]
);
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
res.status(500).json({ message: 'Error registering user' });
}
},

login: async (req, res) => {
const { email, password } = req.body;

try {
const [rows] = await connection.query(
'SELECT * FROM users2 WHERE email = ?',
[email]
);

if (rows.length === 0) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const user = rows[0];
const isPasswordValid = bcrypt.compareSync(password, user.password);

if (!isPasswordValid) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const token = jwt.sign({ id: user.id }, process.env.TOKEN_ACCESS_SECRET, {
expiresIn: '1h',
});

login: async (req, res) => {},
res.cookie('token', token, { httpOnly: true }).status(200).json({
message: 'Login successful',
user: { id: user.id, name: user.name, email: user.email },
});
} catch (error) {
res.status(500).json({ message: 'Error logging in' });
}
},

logout: async (req, res) => {},
logout: (req, res) => {
res.clearCookie('token').status(200).json({ message: 'Logout successful' });
},
};

export default userControllers;
13 changes: 13 additions & 0 deletions css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/* public/style.css */

body {
font-family: Arial, sans-serif;
}

h1 {
color: #333;
}

p {
color: #666;
}
21 changes: 21 additions & 0 deletions database/recipiesmysql.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- database/recipiesMysql.sql

CREATE DATABASE IF NOT EXISTS recipiesMysql;

USE recipiesMysql;

CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS recipes (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT,
user_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
55 changes: 55 additions & 0 deletions database/recipiesmysql_recipes.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
-- MySQL dump 10.13 Distrib 8.0.36, for Win64 (x86_64)
--
-- Host: localhost Database: recipiesmysql
-- ------------------------------------------------------
-- Server version 8.0.37

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `recipes`
--

DROP TABLE IF EXISTS `recipes`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `recipes` (
`id` int NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` text,
`user_id` int DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
CONSTRAINT `recipes_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users2` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `recipes`
--

LOCK TABLES `recipes` WRITE;
/*!40000 ALTER TABLE `recipes` DISABLE KEYS */;
/*!40000 ALTER TABLE `recipes` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2024-07-12 0:35:41
53 changes: 53 additions & 0 deletions database/recipiesmysql_users2.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
-- MySQL dump 10.13 Distrib 8.0.36, for Win64 (x86_64)
--
-- Host: localhost Database: recipiesmysql
-- ------------------------------------------------------
-- Server version 8.0.37

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `users2`
--

DROP TABLE IF EXISTS `users2`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `users2` (
`id` int NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `users2`
--

LOCK TABLES `users2` WRITE;
/*!40000 ALTER TABLE `users2` DISABLE KEYS */;
/*!40000 ALTER TABLE `users2` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2024-07-12 0:35:41
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ import createRecipeTable from './models/recipe.js';
import userRoutes from './routes/user.js';
import recipeRoutes from './routes/recipe.js';

// Initialize environment variables
dotenv.config();


// set port
const PORT = process.env.PORT || 5009;
const PORT = process.env.PORT || 5002;

// Construct path
const __filename = fileURLToPath(import.meta.url);
Expand Down
Loading