Skip to content

Commit 4ea44a0

Browse files
committed
entrega p3
0 parents  commit 4ea44a0

File tree

7 files changed

+251
-0
lines changed

7 files changed

+251
-0
lines changed

.env

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
DENO_URL=mongodb+srv://otherUser:aabb123@cluster-nebrija.s20pq.mongodb.net/?retryWrites=true&w=majority&appName=Cluster-Nebrija

.vscode/settings.json

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"deno.enable": true
3+
}

deno.json

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"tasks": {
3+
"dev": "deno run --allow-read --allow-sys --allow-env --allow-net --watch main.ts"
4+
},
5+
"imports": {
6+
"mongodb": "npm:mongodb@^6.10.0"
7+
}
8+
}

deno.lock

+79
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

main.ts

+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
import { MongoClient, ObjectId } from "mongodb";
2+
import { TasksModel, Task } from "./types.ts";
3+
import { deModeloaTask } from "./utils.ts";
4+
5+
const MONGO_URL = Deno.env.get("MONGO_URL");
6+
if (!MONGO_URL) {
7+
console.log("MONGO_URL not set");
8+
Deno.exit(1);
9+
}
10+
const client = new MongoClient(MONGO_URL);
11+
12+
// Database Name
13+
const dbName = "nebrija-practica3";
14+
await client.connect();
15+
console.log("Connected successfully to server");
16+
const db = client.db(dbName);
17+
18+
const tasksCollection = db.collection<TasksModel>("tasks");
19+
20+
const handler = async (req: Request): Promise<Response> => {
21+
const method = req.method;
22+
const url = new URL(req.url);
23+
const path = url.pathname;
24+
25+
if (method === "GET") {
26+
//mostrar todos las tareas
27+
if (path === "/tasks") {
28+
const tasks = db.collection("tasks");
29+
const tasksList = await tasks.find().toArray();
30+
return new Response(JSON.stringify(tasksList));
31+
}
32+
//buscar con id
33+
else if (path.startsWith("/tasks/")) {
34+
const id = path.split("/")[2]; // Extrae el ID de la ruta
35+
const taskDB = await tasksCollection.findOne({ _id: new ObjectId(id) }); // Busca la tarea en la base de datos
36+
if (!taskDB) {
37+
return new Response(JSON.stringify({ error: "Tarea no encontrada" }), {
38+
status: 404,
39+
});
40+
} else
41+
return new Response(JSON.stringify(deModeloaTask(taskDB)), {
42+
status: 200,
43+
});
44+
}
45+
} else if (method === "POST") {
46+
//crear una nueva actividad
47+
if (path === "/tasks") {
48+
const task = await req.json();
49+
//comprobamos el titulo
50+
if (!task.title) {
51+
return new Response("Bad request", { status: 405 });
52+
}
53+
const userDB = await tasksCollection.findOne({ title: task.title });
54+
if (userDB) return new Response("Bad request", { status: 406 });
55+
//insertamos los valores de la nueva tarea
56+
const { insertedId } = await tasksCollection.insertOne({
57+
title: task.title,
58+
completed: false,
59+
});
60+
61+
//se devuelve la actividad añadida con todos sus valores
62+
return new Response(
63+
JSON.stringify({
64+
id: insertedId,
65+
title: task.title,
66+
completed: false,
67+
}),
68+
{ status: 407 }
69+
);
70+
}
71+
} else if (method === "PUT") {
72+
const path = url.pathname;
73+
if (path.startsWith("/tasks/")) {
74+
const id = path.split("/")[2]; // Extraer el ID
75+
if (!id) {
76+
return new Response("ID de tarea no proporcionado", { status: 400 });
77+
}
78+
79+
//Coger el cuerpo de la solicitud
80+
const body = await req.json();
81+
const { completed } = body;
82+
83+
if (typeof completed !== "boolean") {
84+
//comprobación si es booleano
85+
return new Response("El campo 'completed' debe ser booleano", {
86+
status: 400,
87+
});
88+
}
89+
90+
// Actualizar la tarea en la db
91+
const result = await tasksCollection.updateOne(
92+
{ _id: new ObjectId(id) },
93+
{ $set: { completed } }
94+
);
95+
96+
if (result.matchedCount === 0) {
97+
//comprobación de actualización
98+
return new Response("Tarea no encontrada", { status: 404 });
99+
}
100+
101+
// Recuperar la tarea actualizada
102+
const updatedTask = await tasksCollection.findOne({
103+
_id: new ObjectId(id),
104+
});
105+
if (!updatedTask) {
106+
return new Response("Error al recuperar la tarea actualizada", {
107+
status: 500,
108+
});
109+
}
110+
111+
//Tarea cambiada resultante
112+
return new Response(
113+
JSON.stringify({
114+
id: updatedTask._id.toString(),
115+
title: updatedTask.title,
116+
completed: updatedTask.completed,
117+
}),
118+
{ status: 200 }
119+
);
120+
}
121+
} else if (method === "DELETE" && path.startsWith("/tasks/")) {
122+
// Extraemos el ID
123+
const id = path.split("/")[2];
124+
const { deletedCount } = await tasksCollection.deleteOne({
125+
_id: new ObjectId(id),
126+
}); // Eliminamos la tarea
127+
128+
if (deletedCount === 0) {
129+
return new Response(JSON.stringify({ error: "Tarea no encontrada" }), {
130+
status: 404,
131+
});
132+
}
133+
return new Response(
134+
JSON.stringify({ message: "Tarea eliminada correctamente" }),
135+
{ status: 200 }
136+
);
137+
}
138+
139+
return new Response("Endpoint not found", { status: 404 });
140+
};
141+
Deno.serve({ port: 3000 }, handler);

types.ts

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { MongoClient, OptionalId } from "mongodb";
2+
3+
export type TasksModel = OptionalId<{
4+
title: string;
5+
completed: boolean;
6+
}>;
7+
8+
export type Task = {
9+
id: string;
10+
title: string;
11+
completed: boolean;
12+
};

utils.ts

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import type { TasksModel, Task } from "./types.ts";
2+
3+
export const deModeloaTask = (model: TasksModel): Task => ({
4+
id: model._id!.toString(),
5+
title: model.title,
6+
completed: model.completed,
7+
});

0 commit comments

Comments
 (0)