Skip to content

Commit

Permalink
Merge pull request #113 from Hexastack/112-issue-decouple-frontend-co…
Browse files Browse the repository at this point in the history
…ntext-logic-from-hooks-logic

refactor(frontend): decouple contexts logic from hooks logic
  • Loading branch information
marrouchi authored Sep 30, 2024
2 parents 7b57d50 + 580ac08 commit 6a5abfd
Show file tree
Hide file tree
Showing 11 changed files with 213 additions and 142 deletions.
51 changes: 51 additions & 0 deletions frontend/src/contexts/apiClient.context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import axios from "axios";
import { createContext, ReactNode, FC } from "react";

import { getApiClientByEntity, useAxiosInstance } from "@/hooks/useApiClient";
import { ApiClient, EntityApiClient } from "@/services/api.class";
import { EntityType } from "@/services/types";
import { IBaseSchema } from "@/types/base.types";

interface ApiClientContextProps {
children: ReactNode;
}

export interface ApiClientContext {
apiClient: ApiClient;
getApiClientByEntity: <TAttr, TStub extends IBaseSchema, TFull = never>(
type: EntityType,
) => EntityApiClient<TAttr, TStub, TFull>;
}

export const ApiClientContext = createContext<ApiClientContext>({
apiClient: new ApiClient(axios.create()),
getApiClientByEntity: () => {
throw new Error(
"getApiClientByEntity must be used within an ApiClientProvider",
);
},
});

export const ApiClientProvider: FC<ApiClientContextProps> = ({ children }) => {
const axiosInstance = useAxiosInstance();
const apiClient = new ApiClient(axiosInstance);

return (
<ApiClientContext.Provider
value={{
apiClient,
getApiClientByEntity: (type) => getApiClientByEntity(type, apiClient),
}}
>
{children}
</ApiClientContext.Provider>
);
};
63 changes: 14 additions & 49 deletions frontend/src/hooks/useAuth.tsx → frontend/src/contexts/auth.context.tsx
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,29 @@

import getConfig from "next/config";
import { useRouter } from "next/router";
import React, { createContext, ReactNode, useContext, useState } from "react";
import { useState, useEffect, createContext, ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
useQueryClient,
useQuery,
QueryObserverResult,
RefetchOptions,
UseMutateFunction,
useQuery,
useQueryClient,
} from "react-query";

import { Progress } from "@/app-components/displays/Progress";
import { useLogout } from "@/hooks/entities/auth-hooks";
import { useApiClient } from "@/hooks/useApiClient";
import {
useLogoutRedirection,
CURRENT_USER_KEY,
PUBLIC_PATHS,
} from "@/hooks/useAuth";
import { useToast } from "@/hooks/useToast";
import { RouterType } from "@/services/types";
import { IUser } from "@/types/user.types";
import { getFromQuery } from "@/utils/URL";

import { useLogout } from "./entities/auth-hooks";
import { useApiClient } from "./useApiClient";
import { useToast } from "./useToast";

const { publicRuntimeConfig } = getConfig();

export interface AuthContextValue {
user: IUser | undefined;
isAuthenticated: boolean;
Expand All @@ -41,22 +43,15 @@ export interface AuthContextValue {
error: Error | null;
}

const AuthContext = createContext<AuthContextValue | null>(null);
export const AuthContext = createContext<AuthContextValue | null>(null);

AuthContext.displayName = "AuthContext";

export interface AuthProviderProps {
children: ReactNode;
}

const PUBLIC_PATHS = [
"/login/[[...token]]",
"/register/[token]",
"/reset/[token]",
"/reset",
];

export const CURRENT_USER_KEY = "current-user";
const { publicRuntimeConfig } = getConfig();

export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
const router = useRouter();
Expand Down Expand Up @@ -113,7 +108,7 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
};
const isAuthenticated = !!user;

React.useEffect(() => {
useEffect(() => {
const search = location.search;

setSearch(search);
Expand All @@ -138,33 +133,3 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
</AuthContext.Provider>
);
};

export const useAuth = () => {
const context = useContext(AuthContext);

if (!context) {
throw new Error(`useAuth must be used within an AuthProvider`);
}

return context;
};

export const useLogoutRedirection = () => {
const router = useRouter();
const hasPublicPath = PUBLIC_PATHS.includes(router.pathname);
const logoutRedirection = async (fullReload: boolean = false) => {
if (!hasPublicPath) {
const redirectUrl = `/${RouterType.LOGIN}?redirect=${encodeURIComponent(
router.pathname,
)}`;

if (fullReload) {
window.location.replace(redirectUrl);
} else {
await router.replace(redirectUrl);
}
}
};

return { logoutRedirection };
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { createContext, useContext, useEffect, useState } from "react";
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

const ConfigContext = createContext<IConfig | null>(null);
import { useState, useEffect, createContext } from "react";

export const ConfigContext = createContext<IConfig | null>(null);

export interface IConfig {
apiUrl: string;
Expand Down Expand Up @@ -35,13 +43,3 @@ export const ConfigProvider = ({ children }) => {
<ConfigContext.Provider value={config}>{children}</ConfigContext.Provider>
);
};

export const useConfig = () => {
const context = useContext(ConfigContext);

if (!context) {
throw new Error("useConfig must be used within a ConfigProvider");
}

return context;
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,14 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import {
createContext,
ReactNode,
useCallback,
useContext,
useMemo,
} from "react";
import { createContext, ReactNode, useCallback, useMemo } from "react";

import { Progress } from "@/app-components/displays/Progress";
import { useUserPermissions } from "@/hooks/entities/auth-hooks";
import { EntityType } from "@/services/types";
import { PermissionAction } from "@/types/permission.types";

import { useUserPermissions } from "./entities/auth-hooks";

const PermissionContext = createContext<{
export const PermissionContext = createContext<{
getAllowedActions: (_type: EntityType) => undefined | PermissionAction[];
}>({
getAllowedActions: (_type: EntityType) => undefined,
Expand Down Expand Up @@ -68,17 +61,3 @@ export const PermissionProvider = ({
</PermissionContext.Provider>
);
};

export const useHasPermission = () => {
const { getAllowedActions } = useContext(PermissionContext);
const hasPermission = useCallback(
(type: EntityType, action: PermissionAction) => {
const allowedActions = getAllowedActions(type);

return allowedActions?.includes(action);
},
[getAllowedActions],
);

return hasPermission;
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import { createContext, ReactNode, useContext } from "react";
import { createContext, ReactNode } from "react";

import { Progress } from "@/app-components/displays/Progress";
import { useLoadSettings } from "@/hooks/entities/auth-hooks";
import { ISetting } from "@/types/setting.types";

import { useLoadSettings } from "./entities/auth-hooks";

const SettingsContext = createContext<{
export const SettingsContext = createContext<{
settings: { [key: string]: ISetting[] } | undefined;
}>({ settings: undefined });

Expand All @@ -40,12 +39,3 @@ export const SettingsProvider = ({
</SettingsContext.Provider>
);
};

export const useSetting = (type: string, label: string) => {
const { settings } = useContext(SettingsContext);
const value = settings?.[type]?.find(
(setting) => setting.label === label,
)?.value;

return value;
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@

import axios from "axios";
import { stringify } from "qs";
import React, { createContext, ReactNode, useContext, useMemo } from "react";
import { useContext, useMemo } from "react";
import { useTranslation } from "react-i18next";

import { ApiClientContext } from "@/contexts/apiClient.context";
import { ApiClient, EntityApiClient } from "@/services/api.class";
import { EntityType } from "@/services/types";
import { IBaseSchema } from "@/types/base.types";
Expand Down Expand Up @@ -65,20 +66,13 @@ export const useAxiosInstance = () => {
return axiosInstance;
};

interface ApiClientContextProps {
children: ReactNode;
}

export const entityApiClients = new Map();

interface ApiClientContext {
apiClient: ApiClient;
getApiClientByEntity: <TAttr, TStub extends IBaseSchema, TFull = never>(
type: EntityType,
) => EntityApiClient<TAttr, TStub, TFull>;
}

const getApiClientByEntity = <TAttr, TStub extends IBaseSchema, TFull = never>(
export const getApiClientByEntity = <
TAttr,
TStub extends IBaseSchema,
TFull = never,
>(
type: EntityType,
apiClient: ApiClient,
) => {
Expand All @@ -90,32 +84,6 @@ const getApiClientByEntity = <TAttr, TStub extends IBaseSchema, TFull = never>(

return entityApiClients.get(type) as EntityApiClient<TAttr, TStub, TFull>;
};
const ApiClientContext = createContext<ApiClientContext>({
apiClient: new ApiClient(axios.create()),
getApiClientByEntity: () => {
throw new Error(
"getApiClientByEntity must be used within an ApiClientProvider",
);
},
});

export const ApiClientProvider: React.FC<ApiClientContextProps> = ({
children,
}) => {
const axiosInstance = useAxiosInstance();
const apiClient = new ApiClient(axiosInstance);

return (
<ApiClientContext.Provider
value={{
apiClient,
getApiClientByEntity: (type) => getApiClientByEntity(type, apiClient),
}}
>
{children}
</ApiClientContext.Provider>
);
};

export const useApiClient = (): ApiClientContext => {
const context = useContext(ApiClientContext);
Expand Down
51 changes: 51 additions & 0 deletions frontend/src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import { useRouter } from "next/router";
import { useContext } from "react";

import { AuthContext } from "@/contexts/auth.context";
import { RouterType } from "@/services/types";

export const CURRENT_USER_KEY = "current-user";
export const PUBLIC_PATHS = [
"/login/[[...token]]",
"/register/[token]",
"/reset/[token]",
"/reset",
];

export const useAuth = () => {
const context = useContext(AuthContext);

if (!context) {
throw new Error(`useAuth must be used within an AuthProvider`);
}

return context;
};

export const useLogoutRedirection = () => {
const router = useRouter();
const hasPublicPath = PUBLIC_PATHS.includes(router.pathname);
const logoutRedirection = async (fullReload: boolean = false) => {
if (!hasPublicPath) {
const redirectUrl = `/${RouterType.LOGIN}?redirect=${encodeURIComponent(
router.pathname,
)}`;

if (fullReload) {
window.location.replace(redirectUrl);
} else {
await router.replace(redirectUrl);
}
}
};

return { logoutRedirection };
};
Loading

0 comments on commit 6a5abfd

Please sign in to comment.