From 98d267cc888809ac70ef15e5f4550ff6c11c7979 Mon Sep 17 00:00:00 2001 From: Ranjana Jha <98427281+KBRRM@users.noreply.github.com> Date: Sun, 27 Oct 2024 23:46:43 +0530 Subject: [PATCH] Update todo.ts --- week-10/1-postgres-simple/src/db/todo.ts | 83 ++++++++++++++---------- 1 file changed, 48 insertions(+), 35 deletions(-) diff --git a/week-10/1-postgres-simple/src/db/todo.ts b/week-10/1-postgres-simple/src/db/todo.ts index ae1d8f9eed..cdd46a8caf 100644 --- a/week-10/1-postgres-simple/src/db/todo.ts +++ b/week-10/1-postgres-simple/src/db/todo.ts @@ -1,41 +1,54 @@ import { client } from ".."; -/* - * Function should insert a new todo for this user - * Should return a todo object - * { - * title: string, - * description: string, - * done: boolean, - * id: number - * } - */ -export async function createTodo(userId: number, title: string, description: string) { - + +// Function to create a new todo for a user +export async function createTodo(userId, title, description) { + const result = await client.query(` + INSERT INTO todos (user_id, title, description, done) + VALUES ($1, $2, $3, $4) + RETURNING id, title, description, done; + `, [userId, title, description, false]); + + return { + id: result.rows[0].id, + title: result.rows[0].title, + description: result.rows[0].description, + done: result.rows[0].done + }; } -/* - * mark done as true for this specific todo. - * Should return a todo object - * { - * title: string, - * description: string, - * done: boolean, - * id: number - * } - */ -export async function updateTodo(todoId: number) { +// Function to mark a todo as done +export async function updateTodo(todoId) { + const result = await client.query(` + UPDATE todos + SET done = true + WHERE id = $1 + RETURNING id, title, description, done; + `, [todoId]); + + if (result.rows.length === 0) { + throw new Error(`Todo with ID ${todoId} not found.`); + } + + return { + id: result.rows[0].id, + title: result.rows[0].title, + description: result.rows[0].description, + done: result.rows[0].done + }; } -/* - * Get all the todos of a given user - * Should return an array of todos - * [{ - * title: string, - * description: string, - * done: boolean, - * id: number - * }] - */ -export async function getTodos(userId: number) { +// Function to get all todos for a user +export async function getTodos(userId) { + const result = await client.query(` + SELECT id, title, description, done + FROM todos + WHERE user_id = $1; + `, [userId]); -} \ No newline at end of file + return result.rows.map(row => ({ + id: row.id, + title: row.title, + description: row.description, + done: row.done + })); +}