Skip to content

Commit

Permalink
Server errors + refactor project activities (#90)
Browse files Browse the repository at this point in the history
* added activities into calendar view, both month and week

* chores: fix bug

* refactor weather

* user actions refactor

* project handling

* main page refactor

* refactor server actions

* add separator for different times

* new chats ui

* refactor login and register errors

* fix conflixcts with calendar

* adding activity task onto calendar

* Inglisc

* fix icons

* week show activity project

* adding enums for colors

* working enum

* week button color

* fix colors in calendar

* fix colors in modal

* moving in months

* currentHour fix hook

* resolve building errors

---------
Co-authored-by: SuperMitic <emanuele.2003@yahoo.it>
Co-authored-by: Jabbar03 <ayache.omar@gmail.com>
  • Loading branch information
Diebbo authored Nov 15, 2024
1 parent 746887f commit 80bc1ba
Show file tree
Hide file tree
Showing 31 changed files with 827 additions and 505 deletions.
74 changes: 38 additions & 36 deletions client/actions/auth.action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,48 +20,50 @@ export const deleteAuthCookie = async () => {
};

// Purpose: Handles the login process.
export async function login(user: LoginFormType) {
const response = await fetch(`${getBaseUrl()}/api/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
credentials: "include",
});

if (!response.ok) {
const error = await response.json();
// WE need this to show the error message in the login page
// Doesn't work with throw new Error in production
if (response.status === 401) {
const err = {
message: error.message,
success: false,
};
return err;
export async function login(user: LoginFormType | Error) {
try {
const response = await fetch(`${getBaseUrl()}/api/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
credentials: "include",
});

if (!response.ok) {
const error = await response.json();
console.log(response);
// WE need this to show the error message in the login page
// Doesn't work with throw new Error in production
return new Error(error.message || "Login failed");
}
throw new Error(error.message || "Login failed");
}

return await response.json();
return await response.json();
} catch (error) {
return new Error("Login failed");
}
}

export async function register(user: RegisterType) {
const response = await fetch(`${getBaseUrl()}/api/auth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
});
export async function register(user: RegisterType | Error) {
try {
const response = await fetch(`${getBaseUrl()}/api/auth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user),
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.message || "Registration failed");
}
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || "Registration failed");
}

return response.json();
return response.json();
} catch (error: any) {
return new Error(error?.message || "Registration failed");
}
}

export async function verification(emailToken: string) {
Expand Down
13 changes: 5 additions & 8 deletions client/actions/chats.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { cookies } from 'next/headers';
import getBaseUrl from '@/config/proxy';
import { ChatModel, MessageModel } from '@/helpers/types';

async function getChats() {
async function getChats(): Promise<ChatModel[]> {
const cookieStore = await cookies();
const token = cookieStore.get('token')?.value;

Expand All @@ -25,25 +26,21 @@ async function getChats() {
return await res.json();
}

async function getChatByUsername(username: string) {
async function getChatByUsername(username: string) : Promise<MessageModel[] | Error> {
const cookieStore = await cookies();
const token = cookieStore.get('token')?.value;

if (!token) {
throw new Error('Not authenticated');
}

const res = await fetch(`${getBaseUrl()}/api/chats/messages/${username}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Cookie': `token=${token.toString()}`,
'Cookie': `token=${token?.toString()}`,
},
cache: 'no-store' // This ensures fresh data on every request
});

if (!res.ok) {
throw new Error('Failed to fetch chat');
return new Error('Failed to fetch chat');
}

return await res.json();
Expand Down
111 changes: 62 additions & 49 deletions client/actions/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,69 @@ import { cookies } from "next/headers";
import getBaseUrl from "@/config/proxy";
import { Person, TaskModel } from "@/helpers/types";

export async function getUser(): Promise<Person> {
const cookieStore = await cookies();
const token = cookieStore.get("token")?.value;

if (!token) {
throw new Error("Not authenticated");
}

const response = await fetch(`${getBaseUrl()}/api/users/id`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Cookie: `token=${token.toString()}`,
},
});

if (response.status !== 200) {
async function fetchWithErrorHandling(url: string, options: RequestInit): Promise<Response> {
const response = await fetch(url, options);
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`HTTP error! status: ${response.status}, message: ${errorText}`,
);
throw new Error(errorText || "Request failed");
}
return response;
}

const userData = await response.json();

const person: Person = {
...userData,
events: {
created: userData.events,
participating: userData.participatingEvents,
},
};
export async function getUser(): Promise<Person | Error> {
try {
const cookieStore = await cookies();
const token = cookieStore.get("token")?.value;
const response = await fetchWithErrorHandling(`${getBaseUrl()}/api/users/id`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Cookie: `token=${token?.toString()}`,
},
});

const userData = await response.json();

const person: Person = {
...userData,
events: {
created: userData.events,
participating: userData.participatingEvents,
},
};

return person;
} catch (error) {
return new Error("Failed to fetch user data");
}
}

return person;
export async function getUserByUsername(username: string): Promise<Person | Error> {
try {
const cookieStore = await cookies();
const token = cookieStore.get("token")?.value;
const response = await fetchWithErrorHandling(`${getBaseUrl()}/api/users/usernames/${username}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Cookie: `token=${token?.toString()}`,
},
});

const userData = await response.json();

const person: Person = {
...userData,
events: {
created: userData.events,
participating: userData.participatingEvents,
},
};

return person;
} catch (error) {
return new Error("Failed to fetch user data");
}
}


Expand All @@ -49,7 +78,7 @@ export async function getEmail(): Promise<string> {
throw new Error("Not authenticated");
}

const response = await fetch(`${getBaseUrl()}/api/auth/email`, {
const response = await fetchWithErrorHandling(`${getBaseUrl()}/api/auth/email`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Expand All @@ -58,15 +87,9 @@ export async function getEmail(): Promise<string> {
credentials: "include",
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.message || "Verification failed");
}

return await response.json();
}


export async function getUserTasks(): Promise<TaskModel> {
const cookieStore = await cookies();
const token = cookieStore.get("token")?.value;
Expand All @@ -75,7 +98,7 @@ export async function getUserTasks(): Promise<TaskModel> {
throw new Error("Not authenticated");
}

const response = await fetch(`${getBaseUrl()}/api/user/tasks`, {
const response = await fetchWithErrorHandling(`${getBaseUrl()}/api/user/tasks`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Expand All @@ -84,11 +107,6 @@ export async function getUserTasks(): Promise<TaskModel> {
credentials: "include",
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.message || "Verification failed");
}

return await response.json();
}

Expand All @@ -100,17 +118,12 @@ export async function updateGPS(position: { latitude: number; longitude: number
throw new Error("Not authenticated");
}

const response = await fetch(`${getBaseUrl()}/api/users/gps`, {
await fetchWithErrorHandling(`${getBaseUrl()}/api/users/gps`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Cookie: `token=${token.toString()}`,
},
body: JSON.stringify(position),
});


if (!response.ok) {
throw new Error("Failed to update position");
}
}
7 changes: 6 additions & 1 deletion client/actions/weather.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ export async function getWeather(position: {
);

if (!currentWeatherResponse.ok || !forecastResponse.ok) {
throw new Error("Weather data fetch failed");
return {
current: null,
forecast: null,
error: "Errore nel recupero dei dati meteo",
};
}

const currentData = await currentWeatherResponse.json();
Expand All @@ -42,5 +46,6 @@ export async function getWeather(position: {
weather: reading.weather[0].main,
icon: reading.weather[0].icon,
})),
error: null,
};
}
14 changes: 11 additions & 3 deletions client/app/(app)/calendar/[eventid]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@
import ShowEvent from '@/components/calendar/showEvent';
import { getUser } from "@/actions/user";
import { getEvent, getOwner } from '@/actions/events'
import { showError } from '@/helpers/error-checker';

const EventPage = async ({ params }: { params: Promise<{ eventid: string }> }) => {
const event = await getEvent((await params).eventid);
const user = await getUser();
const owner = await getOwner(String(event.uid));
const [event, user, owner] = await Promise.all([
getEvent((await params).eventid),
getUser(),
getOwner(String((await getEvent((await params).eventid)).uid))
]);

if (user instanceof Error) {
return showError(user);
}


return (
<ShowEvent
Expand Down
39 changes: 21 additions & 18 deletions client/app/(app)/calendar/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,37 @@ import React from "react";
import CalendarPage from "@/components/calendar/calendar";
import { getUser } from "@/actions/user";
import { getCurrentTime } from "@/actions/setTime";
import { Person, People, ProjectModel } from "@/helpers/types";
import { Person, People, ProjectModel, TaskModel } from "@/helpers/types";
import { getFriends } from "@/actions/friends";
import getProjects from "@/actions/projects";
import { getTasks } from "@/actions/tasks";
import getProjects from "@/actions/projects"
import { TaskMutiResponse } from "@/helpers/api-types";
import { showError } from "@/helpers/error-checker";

const Page = async () => {
try {
const [dbDate, friends, user, projects]: [
Date,
People,
Person,
ProjectModel[],
] = await Promise.all([
const [dbDate, friends, user, projects, tasks]: [Date, People, Person | Error, ProjectModel[], TaskMutiResponse] = await Promise.all([
getCurrentTime(),
getFriends(),
getUser(),
getProjects(),
getTasks(),
]);
return (
<CalendarPage
createdEvents={user.events.created}
participatingEvents={user.events.participating}
dbdate={new Date(dbDate)}
friends={friends}
projects={projects}
/>
);

if (user instanceof Error) {
return showError(user);
}

return <CalendarPage
createdEvents={user.events.created}
participatingEvents={user.events.participating}
dbdate={new Date(dbDate)}
friends={friends}
tasks={tasks}
projects={projects}
/>;
} catch (error) {
console.log(error);
return showError(error);
}
};

Expand Down
Loading

0 comments on commit 80bc1ba

Please sign in to comment.