-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
75 lines (64 loc) · 2.01 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Ticket = require('./models/Ticket');
const app = express();
app.use(bodyParser.json());
// Conectar a MongoDB
// mongoose.connect('mongodb://localhost:27017/tickets', { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
app.get("/", function (req, res) {
res.sendFile("index.html", { root: __dirname });
});
// Crear un ticket
app.post('/tickets', async (req, res) => {
try {
const newTicket = new Ticket(req.body);
const savedTicket = await newTicket.save();
res.status(201).json(savedTicket);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Obtener tickets con paginación y filtrado opcional por ID
app.get('/tickets', async (req, res) => {
try {
const { page = 1, limit = 10, userId } = req.query;
const query = userId ? { user: userId } : {};
const tickets = await Ticket.find(query)
.limit(limit * 1)
.skip((page - 1) * limit)
.exec();
const count = await Ticket.countDocuments(query);
res.json({
tickets,
totalPages: Math.ceil(count / limit),
currentPage: page
});
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Editar un ticket
app.put('/tickets/:id', async (req, res) => {
try {
const updatedTicket = await Ticket.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updatedTicket);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Eliminar un ticket
app.delete('/tickets/:id', async (req, res) => {
try {
await Ticket.findByIdAndDelete(req.params.id);
res.status(204).send();
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Iniciar el servidor
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});