Skip to content
Snippets Groups Projects
Commit 6ecd531e authored by hugcubi's avatar hugcubi
Browse files

Poblador automático en node

parent 866fca9e
Branches
Tags
1 merge request!36Develop
node_modules
package-lock.json
\ No newline at end of file
#!/bin/bash
# Configuración de la conexión a MySQL
MYSQL_USER="user" # Usuario de MySQL
MYSQL_PASSWORD="password" # Contraseña del usuario
MYSQL_HOST="localhost" # Dirección del servidor MySQL
MYSQL_PORT="3306" # Puerto de MySQL (3306 por defecto)
# Nombres de las bases de datos a eliminar
DATABASES=("Users" "Hotels" "Bookings")
# Confirmación antes de eliminar
echo "Las siguientes bases de datos serán eliminadas: ${DATABASES[*]}"
read -p "¿Estás seguro de que deseas continuar? (escribe 'yes' para confirmar): " CONFIRMATION
if [ "$CONFIRMATION" != "yes" ]; then
echo "Cancelado. Las bases de datos no se eliminarán."
exit 1
fi
# Eliminar cada base de datos
for DB in "${DATABASES[@]}"; do
echo "Eliminando base de datos: $DB"
mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -h"$MYSQL_HOST" -P"$MYSQL_PORT" -e "DROP DATABASE IF EXISTS $DB;"
if [ $? -eq 0 ]; then
echo "Base de datos $DB eliminada correctamente."
else
echo "Error al eliminar la base de datos $DB."
fi
done
echo "Proceso completado."
export const env = {
authApi: "http://localhost:8101/",
userApi: "http://localhost:8201/users",
hotelsApi: "http://localhost:8301/hotels",
bookingsApi: "http://localhost:8401/bookings",
};
export const env = {
authApi: "http://localhost:8101/",
userApi: "http://localhost:8201/users",
hotelsApi: "http://localhost:8301/hotels",
bookingsApi: "http://localhost:8401/bookings",
};
const mockedUsers = require("./mocks/users.json");
const mockedHotels = require("./mocks/hotels.json");
const mockedBookings = require("./mocks/bookings.json");
const axios = require("axios");
const { jwtDecode } = require("jwt-decode");
// Modo
const args = process.argv;
const isProduction = args.includes("--prod");
const authUrl = "http://localhost:8101/auth";
const hotelsUrl = "http://localhost:8301/hotels";
const bookingUrl = "http://localhost:8401/bookings";
const loj = (data) => {
console.log(JSON.stringify(data, null, 2));
};
// Función para calcular fechas pareadas
function genDates(ref = new Date()) {
// before
const beforeStart = new Date(ref);
beforeStart.setDate(ref.getDate() - 14); // Restar 2 semanas
const beforeEnd = new Date(beforeStart);
beforeEnd.setDate(beforeStart.getDate() + 3);
// After
const afterStart = new Date(ref);
afterStart.setDate(ref.getDate() + 14); // Restar 2 semanas
const afterEnd = new Date(afterStart);
afterEnd.setDate(afterStart.getDate() + 2);
return [
{
start: beforeStart,
end: beforeEnd,
},
{
start: afterStart,
end: afterEnd,
},
];
}
function getRandomItem(a = []) {
return a[Math.floor(Math.random() * a.length)];
}
const savePost = async (data, first, second = "") => {
try {
try {
return await axios.post(first, data);
} catch (error) {
console.error("ERROR 1");
return await axios.post(second, data);
}
} catch (error) {
console.error("ERROR 2");
process.exit(-1);
}
};
async function register(user) {
const { data } = await savePost(
user,
`${authUrl}/register`,
`${authUrl}/login`
);
const decoded = jwtDecode(data.token);
user.id = decoded.id;
return user;
}
const addUsers = async () => {
const users = [];
for await (const user of mockedUsers) {
users.push(await register(user));
}
const admins = users.filter((u) => u.rol === "ADMIN");
const managers = users.filter((u) => u.rol === "HOTEL_ADMIN");
const clients = users.filter((u) => u.rol === "CLIENT");
return { admins, managers, clients };
};
const insertHotel = async ({ manager, hotel }) => {
const { data } = await axios.post(hotelsUrl, {
...hotel,
managerId: manager.id,
});
return data;
};
async function addHotels(managers) {
const hotels = [];
for await (const hotel of mockedHotels) {
const select = getRandomItem(managers);
hotels.push(await insertHotel({ hotel, manager: select }));
}
return hotels;
}
const insertBookings = async (booking) => {
console.log({ booking });
const { data } = await axios.post(bookingUrl, booking);
return data;
};
async function addBookings(clients, hotels) {
var i = 0;
const t = hotels.length;
for await (const hotel of hotels) {
const roomId = getRandomItem(hotel.rooms.filter((r) => r.available)).id;
const userId = getRandomItem(clients).id;
const des = (i - t / 2) * 15;
const date = new Date();
date.setDate(date.getDate() + des);
for await (const dates of genDates(date)) {
await insertBookings({
managerId: hotel.managerId,
userId,
hotelId: hotel.id,
roomId,
...dates,
});
}
}
}
async function init() {
const { managers, clients } = await addUsers();
const hotels = await addHotels(managers, 3);
await addBookings(clients, hotels);
}
console.log("MODE:", isProduction ? "PRODUCTION" : "DEVELOPMENT");
init();
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
"clientId": 1, "clientId": 1,
"hotelId": 1, "hotelId": 1,
"roomId": 2, "roomId": 2,
"managerId": 3,
"startDate": "2024-10-20", "startDate": "2024-10-20",
"endDate": "2024-10-25" "endDate": "2024-10-25"
}, },
...@@ -10,6 +11,7 @@ ...@@ -10,6 +11,7 @@
"clientId": 3, "clientId": 3,
"hotelId": 2, "hotelId": 2,
"roomId": 3, "roomId": 3,
"managerId": 4,
"startDate": "2025-02-22", "startDate": "2025-02-22",
"endDate": "2025-02-27" "endDate": "2025-02-27"
} }
......
...@@ -42,6 +42,16 @@ ...@@ -42,6 +42,16 @@
"roomNumber": "202", "roomNumber": "202",
"type": "SUITE", "type": "SUITE",
"available": true "available": true
},
{
"roomNumber": "203",
"type": "SUITE",
"available": true
},
{
"roomNumber": "204",
"type": "SUITE",
"available": false
} }
] ]
} }
......
[ [
{ {
"name": "John Doe", "name": "ADMIN",
"email": "john.doe@example.com", "email": "admin@dev.com",
"password": "securePassword123", "password": "123",
"rol": "CLIENT" "rol": "ADMIN"
}, },
{ {
"name": "Jane Smith", "name": "Hotel",
"email": "jane.smith@example.com", "email": "hotel@dev.com",
"password": "securePassword456", "password": "123",
"rol": "HOTEL_ADMIN" "rol": "HOTEL_ADMIN"
}, },
{ {
"name": "Alice Johnson", "name": "Client",
"email": "alice.johnson@example.com", "email": "client@dev.com",
"password": "securePassword789", "password": "123",
"rol": "CLIENT" "rol": "CLIENT"
} }
] ]
{
"name": "poblate",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "node index.js",
"prod": "node index.js -- --prod",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"axios": "^1.7.9",
"jwt-decode": "^4.0.0"
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment