Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/auth architecture pt4 #279

Merged
merged 16 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ import {
import { useUser } from "@/store/hooks";

export const useCalendarLogic = () => {
const { currentDate } = useUser();
const today = useMemo(() => currentDate ?? new Date(), [currentDate]);
const { currentDateInUserTimezone } = useUser();
const today = useMemo(
() => currentDateInUserTimezone ?? new Date(),
[currentDateInUserTimezone],
);

const [date, setDate] = useState<Date>(today);
const [selectedDate, setSelectedDate] = useState<Date>(today);
Expand Down
6 changes: 3 additions & 3 deletions src/app/(main)/dashboard/components/Calendar/Events.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const useEventsLogic = (
voyageNumber?: number | null,
teamId?: string,
) => {
const { timezone, currentDate } = useUser();
const { timezone, currentDateInUserTimezone } = useUser();

const voyageStartDate = sprintsData?.find(
(sprint) => Number(sprint.number) === 1,
Expand Down Expand Up @@ -157,7 +157,7 @@ export const useEventsLogic = (
check: true,
label: "Weekly Check-in Due",
link: getWeeklyCheckInLink(),
isDisabled: isBefore(date, currentDate ?? new Date()),
isDisabled: isBefore(date, currentDateInUserTimezone ?? new Date()),
showDot: true,
});
}
Expand All @@ -168,7 +168,7 @@ export const useEventsLogic = (
check: true,
label: "Voyage Submission Due",
link: getSubmitVoyageLink(),
isDisabled: isBefore(date, currentDate ?? new Date()),
isDisabled: isBefore(date, currentDateInUserTimezone ?? new Date()),
showDot: true,
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ function CheckInWidget({
currentSprintNumber,
teamId,
}: CheckInWidgetProps) {
const { timezone, currentDate } = useUser();
const { timezone, currentDateInUserTimezone } = useUser();
const sprintsData = useSprint();
const userDate = currentDate ?? new Date();
const userDate = currentDateInUserTimezone ?? new Date();

const sprintCheckinIsSubmitted = getSprintCheckinIsStatus(
user,
Expand Down
51 changes: 46 additions & 5 deletions src/app/(main)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,61 @@
"use client";

import "reflect-metadata";
import { useQuery } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { type UserClientAdapter } from "@/modules/user/adapters/primary/userClientAdapter";
import Sidebar from "@/components/sidebar/Sidebar";
import Navbar from "@/components/navbar/Navbar";
import ModeToggle from "@/components/ModeToggle";
import AuthHeader from "@/components/navbar/AuthHeader";
import { getUser } from "@/utils/getUser";
import AuthProvider from "@/app/(auth)/AuthProvider";
import { useAppDispatch } from "@/store/hooks";
import { clientSignIn } from "@/store/features/auth/authSlice";
import routePaths from "@/utils/routePaths";
import { getUserState } from "@/store/features/user/userSlice";
import { TYPES } from "@/di/types";
import { resolve } from "@/di/resolver";
import Spinner from "@/components/Spinner";
import { CacheTag } from "@/utils/cacheTag";

interface LayoutProps {
children: React.ReactNode;
}

export default async function Layout({ children }: LayoutProps) {
const [user, error] = await getUser();
export default function Layout({ children }: LayoutProps) {
const dispatch = useAppDispatch();
const router = useRouter();

const { isPending, isError, data } = useQuery({
queryKey: [CacheTag.me],
queryFn: getUserQuery,
staleTime: 1000 * 60 * 30, // This sets it to 30 minutes, which is how long the access token lasts
});

async function getUserQuery() {
const userAdapter = resolve<UserClientAdapter>(TYPES.UserClientAdapter);
return await userAdapter.getUser();
}

if (isPending) {
return (
<div className="flex min-h-screen items-center justify-center">
<Spinner />
</div>
);
}

// TODO: refactor
if (isError) {
router.push(routePaths.signIn());
}

if (data) {
dispatch(clientSignIn());
dispatch(getUserState(data));
}

return (
<div className="flex h-screen w-screen flex-col">
<AuthProvider user={user} error={error} />
<Navbar>
<>
<ModeToggle />
Expand Down
6 changes: 5 additions & 1 deletion src/components/navbar/DropDown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "reflect-metadata";
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import Button from "@/components/Button";
import { useAppDispatch, useUser } from "@/store/hooks";
import { clientSignOut } from "@/store/features/auth/authSlice";
Expand All @@ -14,12 +14,14 @@ import { type AuthClientAdapter } from "@/modules/auth/adapters/primary/authClie
import routePaths from "@/utils/routePaths";
import type { LogoutResponseDto } from "@/modules/auth/application/dtos/response.dto";
import { onOpenModal } from "@/store/features/modal/modalSlice";
import { CacheTag } from "@/utils/cacheTag";

interface DropdownProps {
openState?: boolean;
}

export default function DropDown({ openState }: DropdownProps) {
const queryClient = useQueryClient();
const router = useRouter();
const dispatch = useAppDispatch();
const allVoyages = useUser().voyageTeamMembers;
Expand Down Expand Up @@ -53,8 +55,10 @@ export default function DropDown({ openState }: DropdownProps) {
}

const { mutate } = useMutation<LogoutResponseDto, Error, void>({
mutationKey: [CacheTag.logout],
mutationFn: logoutMutation,
onSuccess: () => {
queryClient.removeQueries({ queryKey: [CacheTag.me] });
dispatch(clientSignOut());
router.replace(routePaths.signIn());
},
Expand Down
6 changes: 6 additions & 0 deletions src/di/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ import { AxiosAdapter } from "@/modules/restApi/adapters/secondary/AxiosAdapter"
import { AuthClientAdapter } from "@/modules/auth/adapters/primary/authClientAdapter";
import { LoginUsecase } from "@/modules/auth/application/usecases/loginUsecase";
import { LogoutUsecase } from "@/modules/auth/application/usecases/logoutUsecase";
import { UserClientAdapter } from "@/modules/user/adapters/primary/userClientAdapter";
import { GetUserUsecase } from "@/modules/user/application/usecases/getUserUsecase";
import { UserApiAdapter } from "@/modules/user/adapters/secondary/userApiAdapter";

container.register(TYPES.RestApiPort, { useClass: AxiosAdapter });
container.register(TYPES.AuthApiPort, { useClass: AuthApiAdapter });
container.register(TYPES.UserApiPort, { useClass: UserApiAdapter });
container.register(TYPES.LoginUsecase, { useClass: LoginUsecase });
container.register(TYPES.LogoutUsecase, { useClass: LogoutUsecase });
container.register(TYPES.AuthClientAdapter, { useClass: AuthClientAdapter });
container.register(TYPES.GetUserUsecase, { useClass: GetUserUsecase });
container.register(TYPES.UserClientAdapter, { useClass: UserClientAdapter });

export default container;
6 changes: 3 additions & 3 deletions src/di/types.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
export const TYPES = {
/* Ports */
RestApiPort: Symbol.for("RestApiPort"),
AuthClientPort: Symbol.for("AuthClientPort"),
AuthApiPort: Symbol.for("AuthApiPort"),
UserApiPort: Symbol.for("UserApiPort"),

/* Adapters */
AxiosAdapter: Symbol.for("AxiosAdapter"),
AuthClientAdapter: Symbol.for("AuthClientAdapter"),
AuthApiAdapter: Symbol.for("AuthApiAdapter"),
UserClientAdapter: Symbol.for("UserClientAdapter"),

/* UseCases */
LoginUsecase: Symbol.for("LoginUsecase"),
LogoutUsecase: Symbol.for("LogoutUsecase"),
GetUserUsecase: Symbol.for("GetUserUsecase"),
};
6 changes: 3 additions & 3 deletions src/modules/auth/adapters/secondary/authApiAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type {
LogoutResponseDto,
LoginResponseDto,
} from "@/modules/auth/application/dtos/response.dto";
import { AuthUrls } from "@/modules/auth/application/constants/authUrls";
import AuthUrls from "@/modules/auth/application/constants/authUrls";

@injectable()
export class AuthApiAdapter implements AuthApiPort {
Expand All @@ -18,14 +18,14 @@ export class AuthApiAdapter implements AuthApiPort {

async login({ email, password }: LoginRequestDto): Promise<LoginResponseDto> {
return await this.apiClient.post({
url: AuthUrls.login,
url: AuthUrls.login(),
payload: { email, password },
});
}

async logout(): Promise<LogoutResponseDto> {
return await this.apiClient.post({
url: AuthUrls.logout,
url: AuthUrls.logout(),
});
}
}
12 changes: 9 additions & 3 deletions src/modules/auth/application/constants/authUrls.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
export const AuthUrls = {
login: "/api/v1/auth/login",
logout: "/api/v1/auth/logout",
const AuthUrls = {
login() {
return "/api/v1/auth/login";
},
logout() {
return "/api/v1/auth/logout";
},
} as const;

export default AuthUrls;
2 changes: 2 additions & 0 deletions src/modules/restApi/application/entities/requestOptions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// TODO: remove later

export interface RequestOptions {
token?: string;
cache?: RequestCache;
Expand Down
4 changes: 3 additions & 1 deletion src/modules/restApi/application/entities/restApiParams.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// TODO: refactor

import { type RequestOptions } from "./requestOptions";

export interface GetParams {
url: string;
options: RequestOptions;
// options: RequestOptions;
}

export interface PostParams<X> {
Expand Down
17 changes: 17 additions & 0 deletions src/modules/user/adapters/primary/userClientAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { inject, injectable } from "tsyringe";
import { TYPES } from "@/di/types";
import { type UserClientPort } from "@/modules/user/ports/primary/userClientPort";
import { type GetUserResponseDto } from "@/modules/user/application/dtos/response.dto";
import { GetUserUsecase } from "@/modules/user/application/usecases/getUserUsecase";

@injectable()
export class UserClientAdapter implements UserClientPort {
constructor(
@inject(TYPES.GetUserUsecase)
private readonly getUserUsecase: GetUserUsecase,
) {}

async getUser(): Promise<GetUserResponseDto> {
return await this.getUserUsecase.execute();
}
}
20 changes: 20 additions & 0 deletions src/modules/user/adapters/secondary/userApiAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { inject, injectable } from "tsyringe";
import { TYPES } from "@/di/types";
import { type RestApiPort } from "@/modules/restApi/ports/secondary/restApiPort";
import { type UserApiPort } from "@/modules/user/ports/secondary/userApiPort";
import { type GetUserResponseDto } from "@/modules/user/application/dtos/response.dto";
import UserUrls from "@/modules/user/application/constants/userUrls";

@injectable()
export class UserApiAdapter implements UserApiPort {
constructor(
@inject(TYPES.RestApiPort)
private readonly apiClient: RestApiPort,
) {}

async getUser(): Promise<GetUserResponseDto> {
return await this.apiClient.get({
url: UserUrls.getUser(),
});
}
}
7 changes: 7 additions & 0 deletions src/modules/user/application/constants/userUrls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const UserUrls = {
getUser() {
return "/api/v1/users/me";
},
} as const;

export default UserUrls;
46 changes: 46 additions & 0 deletions src/modules/user/application/dtos/response.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
export interface GetUserResponseDto {
id: string;
firstName: string;
lastName: string;
countryCode: string;
oAuthProfiles: {
provider: {
name: providerType;
};
providerUsername: string;
}[];
email: string;
timezone: string;
avatar: string;
voyageTeamMembers: VoyageTeamMember[];
sprintCheckIn: number[];
currentDateInUserTimezone: Date | null;
}

type providerType = "discord";

// TODO: move this to separate module
export interface VoyageTeamMember {
id: number;
voyageTeamId: number;
voyageTeam: VoyageTeam;
voyageRole: VoyageRole;
}

export interface VoyageStatus {
name: string;
}

interface Voyage {
status: VoyageStatus;
}

interface VoyageTeam {
name: string;
voyage: Voyage;
projectSubmitted: boolean;
}

export interface VoyageRole {
name: string;
}
30 changes: 30 additions & 0 deletions src/modules/user/application/usecases/getUserUsecase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { inject, injectable } from "tsyringe";
import { TYPES } from "@/di/types";
import { type UserApiPort } from "@/modules/user/ports/secondary/userApiPort";
import { type GetUserResponseDto } from "@/modules/user/application/dtos/response.dto";
import { transformDateToUserTimezone } from "@/modules/user/application/utils/dateTransform";
import { currentDate } from "@/utils/getCurrentSprint";

@injectable()
export class GetUserUsecase {
constructor(
@inject(TYPES.UserApiPort)
private readonly userApi: UserApiPort,
) {}

async execute(): Promise<GetUserResponseDto> {
const data = await this.userApi.getUser();

// TODO: refactor later
// need to move the current date to a module
const userWithDate = {
...data,
currentDateInUserTimezone: transformDateToUserTimezone(
currentDate,
data.timezone,
),
};

return userWithDate;
}
}
9 changes: 9 additions & 0 deletions src/modules/user/application/utils/dateTransform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { formatInTimeZone } from "date-fns-tz";

export function transformDateToUserTimezone(
date: Date,
timezone: string,
): Date {
const formattedDate = formatInTimeZone(date, timezone, "yyyy-MM-dd HH:mm:ss");
return new Date(formattedDate);
}
5 changes: 5 additions & 0 deletions src/modules/user/ports/primary/userClientPort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type GetUserResponseDto } from "@/modules/user/application/dtos/response.dto";

export interface UserClientPort {
getUser: () => Promise<GetUserResponseDto>;
}
5 changes: 5 additions & 0 deletions src/modules/user/ports/secondary/userApiPort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type GetUserResponseDto } from "@/modules/user/application/dtos/response.dto";

export interface UserApiPort {
getUser: () => Promise<GetUserResponseDto>;
}
Loading
Loading