Skip to content

Commit

Permalink
endpoint de subscriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
RyuDSora committed Aug 2, 2024
1 parent 267228b commit 2a7ffc4
Show file tree
Hide file tree
Showing 4 changed files with 140 additions and 4 deletions.
5 changes: 4 additions & 1 deletion client/src/components/Urls.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,7 @@ export const uritutor = url + '/teachers';
export const uritutorsubject = url + '/ts';

//chats
export const urichat = url + '/api/messages';
export const urichat = url + '/api/messages';

//suscripciones
export const URLsuscription = url + '/suscription';
13 changes: 10 additions & 3 deletions server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import ratingRoute from './routes/ratingRoute.js';
import tutorsubjectRoute from './routes/tutorsubjectRoute.js';
import chatRoutes from './routes/chatRoutes.js';
import stripeRoute from './routes/stripeRoute.js'
import suscriptionRoute from './routes/suscriptionRoute.js'


const app = express();
Expand Down Expand Up @@ -44,11 +45,12 @@ app.use('/ratings', ratingRoute);
app.use('/ts', tutorsubjectRoute);
app.use('/api', chatRoutes);
app.use('/stripe',stripeRoute);
app.use('/suscription',suscriptionRoute);


// Configuración de servidor HTTP y socket.io --aunq no funciona como deberia XD
const server = http.createServer(app);
const io = new Server(server, {
const serverIO = http.createServer(app);
const io = new Server(serverIO, {
cors: {
origin: ['https://tu-torias.vercel.app', 'http://localhost:5173'],
methods: ['GET', 'POST'],
Expand Down Expand Up @@ -82,10 +84,15 @@ io.on('connection', (socket) => {
});

//servidor principal con NodeJS
server.listen(port, () => {
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

//servidor principal con NodeJS
serverIO.listen(3001, () => {
console.log(`ServerIO is running on port ${3001}`);
});

app.get('/', (req, res) => {
res.status(200).send('Bienvenido al servidor de Tutorias. ');
});
100 changes: 100 additions & 0 deletions server/controllers/suscriptionController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import pool from '../database/db.js';

// Mostrar todos los registros de suscripciones
export const getAllSuscrptions = async (req, res) => {
const client = await pool.connect();
try {
const result = await client.query('SELECT * FROM subscriptions');
res.json(result.rows);
} catch (error) {
console.error('Error fetching subscriptions:', error);
res.status(500).send('Error fetching subscriptions.');
} finally {
client.release();
}
};

// Mostrar un registro de suscripcion
export const getSubscriptions = async (req, res) => {
const { id } = req.params;
const client = await pool.connect();
try {
const result = await client.query('SELECT * FROM subscriptions WHERE user_id = $1', [id]);
if (result.rows.length === 0) {
res.status(404).send('subscriptions not found.');
} else {
res.json(result.rows[0]);
}
} catch (error) {
console.error('Error fetching subscriptions:', error);
res.status(500).send('Error fetching subscriptions.');
} finally {
client.release();
}
};

// Crear una nueva suscripcion
export const createSubscriptions = async (req, res) => {
const { user_id, plan_id, subscription_date, status } = req.body;
const client = await pool.connect();
try {
const insertQuery = `
INSERT INTO subscriptions (user_id, plan_id, subscription_date, status)
VALUES ($1, $2, $3, $4)
RETURNING *;
`;
const result = await client.query(insertQuery, [user_id, plan_id, subscription_date, status]);
res.status(201).json(result.rows[0]);
} catch (error) {
console.error('Error inserting subscriptions:', error);
res.status(500).send('Error inserting subscriptions.');
} finally {
client.release();
}
};

// Actualizar una suscripcion existente
export const updateSubscriptions = async (req, res) => {
const { id } = req.params;
const { user_id, plan_id, subscription_date, status } = req.body;
const client = await pool.connect();
try {
const updateQuery = `
UPDATE subscriptions
SET user_id = $1, plan_id = $2, subscription_date = $3, status = $4
WHERE id = $5
RETURNING *;
`;
const result = await client.query(updateQuery, [user_id, plan_id, subscription_date, status, id]);
if (result.rows.length === 0) {
res.status(404).send('subscriptions not found.');
} else {
res.json(result.rows[0]);
}
} catch (error) {
console.error('Error updating subscriptions:', error);
res.status(500).send('Error updating subscriptions.');
} finally {
client.release();
}
};

// Eliminar una suscripcion
export const deletesubscriptions = async (req, res) => {
const { id } = req.params;
const client = await pool.connect();
try {
const deleteQuery = 'DELETE FROM subscriptions WHERE id = $1 RETURNING *';
const result = await client.query(deleteQuery, [id]);
if (result.rows.length === 0) {
res.status(404).send('subscriptions not found.');
} else {
res.json(result.rows[0]);
}
} catch (error) {
console.error('Error deleting subscriptions:', error);
res.status(500).send('Error deleting subscriptions.');
} finally {
client.release();
}
};
26 changes: 26 additions & 0 deletions server/routes/suscriptionRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import express from 'express';
import { getAllSuscrptions, getSubscriptions, createSubscriptions, updateSubscriptions, deletesubscriptions } from '../controllers/suscriptionController.js';
import rateLimit from 'express-rate-limit';

const router = express.Router();
// Configura el limitador de velocidad para rutas sensibles
const sensitiveRouteLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutos
max: 50, // máximo 50 solicitudes por ventana de tiempo
message: 'Too many requests from this IP, please try again after 15 minutes' // mensaje de error personalizado
});

// Configura el limitador de velocidad general (si decides usarlo)
const generalLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutos
max: 100, // máximo 100 solicitudes por ventana de tiempo
message: 'Too many requests from this IP, please try again after 15 minutes' // mensaje de error personalizado
});
// Rutas del Profesor
router.get('/', generalLimiter, getAllSuscrptions);
router.get('/:id', generalLimiter, getSubscriptions);
router.post('/', sensitiveRouteLimiter,createSubscriptions);
router.put('/:id', sensitiveRouteLimiter,updateSubscriptions);
router.delete('/:id', sensitiveRouteLimiter,deletesubscriptions);

export default router;

0 comments on commit 2a7ffc4

Please sign in to comment.