Skip to content

Commit 1cba9c8

Browse files
authored
Merge pull request #7 from jesieldotdev/new-db
fix
2 parents 682d888 + f057b51 commit 1cba9c8

File tree

2 files changed

+111
-24
lines changed

2 files changed

+111
-24
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { getTaskById, updateTaskStatus } from "@/app/lib/tasks_controller";
2+
import { NextResponse } from "next/server";
3+
4+
export const PATCH = async (req: Request, { params }: { params: { id: string } }) => {
5+
try {
6+
const { id } = params; // Acessando o ID via params para maior clareza
7+
const { status } = await req.json();
8+
9+
// Verificar se o status é válido
10+
if (!['incomplete', 'completed'].includes(status)) {
11+
return NextResponse.json({ message: 'Invalid status value' }, { status: 400 });
12+
}
13+
14+
// Chamar a função para atualizar o status da tarefa
15+
const updatedTask = await updateTaskStatus(Number(id), status);
16+
17+
return NextResponse.json({ message: "Task status updated successfully", task: updatedTask }, { status: 200 });
18+
} catch (err) {
19+
if (err instanceof Error) {
20+
console.error('Erro ao atualizar status da tarefa:', err); // Log de erro
21+
return NextResponse.json({ message: 'Internal server error', error: err.message }, { status: 500 });
22+
} else {
23+
console.error('Erro desconhecido:', err); // Log de erro
24+
return NextResponse.json({ message: 'Unknown error occurred' }, { status: 500 });
25+
}
26+
}
27+
};
28+
29+
30+
export const GET = async (req: Request) => {
31+
try {
32+
const id = req.url.split("tasks/status")[1]
33+
const task = await getTaskById(id)
34+
35+
36+
if (!task) {
37+
return NextResponse.json({ message: "Error" }, { status: 404 });
38+
}
39+
40+
41+
return NextResponse.json({ message: "OK", task}, { status: 200 });
42+
} catch (err) {
43+
NextResponse.json({ message: "Error", err }, { status: 500 });
44+
}
45+
};

src/app/lib/tasks_controller.ts

Lines changed: 66 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -42,30 +42,72 @@ export const deleteTask = async (id: string) => {
4242

4343

4444
export const updateTask = async (id: string | number, updatedData: Partial<TaskInput>) => {
45-
console.log('Updating task with ID: ', id);
46-
47-
// Confirme se a tarefa existe antes de tentar atualizar
48-
const { data: task, error: taskError } = await supabase
49-
.from('tasks')
50-
.select('*')
51-
.eq('id', id)
52-
.single();
53-
54-
if (taskError) throw new Error(`Error fetching task: ${taskError.message}`);
55-
if (!task) throw new Error(`No task found with the given id: ${id}`);
56-
57-
// Atualiza apenas os campos passados na requisição
58-
const { data, error } = await supabase
59-
.from('tasks')
60-
.update(updatedData)
61-
.eq('id', Number(id)); // Garantir que o id seja numérico
62-
63-
if (error) throw new Error(`Error updating task: ${error.message}`);
64-
65-
console.log('Updated task: ', data); // Verifique a resposta
66-
67-
return data;
68-
};
45+
console.log('Updating task with ID: ', id);
46+
47+
// Confirme se a tarefa existe antes de tentar atualizar
48+
const { data: task, error: taskError } = await supabase
49+
.from('tasks')
50+
.select('*')
51+
.eq('id', id)
52+
.single();
53+
54+
if (taskError) throw new Error(`Error fetching task: ${taskError.message}`);
55+
if (!task) throw new Error(`No task found with the given id: ${id}`);
56+
57+
// Atualiza apenas os campos passados na requisição
58+
const { data, error } = await supabase
59+
.from('tasks')
60+
.update(updatedData)
61+
.eq('id', Number(id)); // Garantir que o id seja numérico
62+
63+
if (error) throw new Error(`Error updating task: ${error.message}`);
64+
65+
console.log('Updated task: ', data); // Verifique a resposta
66+
67+
return data;
68+
};
69+
70+
export const updateTaskStatus = async (id: string | number, status: 'incomplete' | 'completed') => {
71+
console.log('Updating status for task with ID: ', id);
72+
73+
// Verifica se o status é válido antes de enviar a requisição
74+
if (!['incomplete', 'completed'].includes(status)) {
75+
throw new Error('Invalid status value');
76+
}
77+
78+
// Atualiza a coluna status da tarefa com o ID fornecido
79+
const { data, error } = await supabase
80+
.from('tasks')
81+
.update({ status })
82+
.eq('id', id);
83+
84+
// Verifica se houve erro na atualização
85+
if (error) {
86+
console.error('Error updating task status: ', error.message);
87+
throw new Error(`Error updating task status: ${error.message}`);
88+
}
89+
90+
// Após a atualização, consulta a tarefa atualizada
91+
const { data: updatedData, error: fetchError } = await supabase
92+
.from('tasks')
93+
.select('*')
94+
.eq('id', id)
95+
.single(); // Garante que apenas um item seja retornado
96+
97+
// Verifica se houve erro ao buscar os dados atualizados
98+
if (fetchError) {
99+
console.error('Error fetching updated task: ', fetchError.message);
100+
throw new Error(`Error fetching updated task: ${fetchError.message}`);
101+
}
102+
103+
console.log('Updated task status: ', updatedData);
104+
105+
// Retorna os dados da tarefa atualizada
106+
return updatedData;
107+
};
108+
109+
110+
69111

70112

71113

0 commit comments

Comments
 (0)