mirror of
https://github.com/hexastack/hexabot
synced 2025-06-26 18:27:28 +00:00
fix: config fetched on runtime
This commit is contained in:
parent
aa05fe1704
commit
cdf8461312
@ -1,8 +1,6 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
import withTM from "next-transpile-modules";
|
||||
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_ORIGIN || "http://localhost:4000/";
|
||||
const url = new URL(apiUrl);
|
||||
const nextConfig = withTM(["hexabot-widget"])({
|
||||
async rewrites() {
|
||||
return [
|
||||
@ -16,29 +14,11 @@ const nextConfig = withTM(["hexabot-widget"])({
|
||||
return config;
|
||||
},
|
||||
publicRuntimeConfig: {
|
||||
apiUrl,
|
||||
ssoEnabled: process.env.NEXT_PUBLIC_SSO_ENABLED === "true",
|
||||
lang: {
|
||||
default: "en",
|
||||
},
|
||||
},
|
||||
output: "standalone",
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
pathname: "/attachment/**",
|
||||
},
|
||||
{
|
||||
protocol: "http",
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
pathname: "/attachment/**",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
export default nextConfig;
|
||||
|
@ -11,12 +11,15 @@ import { Grid } from "@mui/material";
|
||||
import { GridRenderCellParams } from "@mui/x-data-grid";
|
||||
|
||||
import { getAvatarSrc } from "@/components/inbox/helpers/mapMessages";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { EntityType } from "@/services/types";
|
||||
|
||||
export const buildRenderPicture = (
|
||||
entityType: EntityType.USER | EntityType.SUBSCRIBER,
|
||||
) =>
|
||||
function RenderPicture(params: GridRenderCellParams) {
|
||||
const { apiUrl } = useConfig();
|
||||
|
||||
return (
|
||||
<Grid
|
||||
container
|
||||
@ -28,6 +31,7 @@ export const buildRenderPicture = (
|
||||
>
|
||||
<img
|
||||
src={getAvatarSrc(
|
||||
apiUrl,
|
||||
entityType,
|
||||
entityType === EntityType.USER
|
||||
? params.row.id
|
||||
|
@ -21,9 +21,9 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useCreate } from "@/hooks/crud/useCreate";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { EntityType } from "@/services/types";
|
||||
|
||||
|
||||
import { ChatActions } from "./ChatActions";
|
||||
import { ChatHeader } from "./ChatHeader";
|
||||
import {
|
||||
@ -35,6 +35,7 @@ import { useChat } from "../hooks/ChatContext";
|
||||
import { useInfinitedLiveMessages } from "../hooks/useInfiniteLiveMessages";
|
||||
|
||||
export function Chat() {
|
||||
const { apiUrl } = useConfig();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { subscriber } = useChat();
|
||||
const { user } = useAuth();
|
||||
@ -69,7 +70,11 @@ export function Chat() {
|
||||
<ConversationHeader>
|
||||
<Avatar
|
||||
name={subscriber?.first_name}
|
||||
src={getAvatarSrc(EntityType.SUBSCRIBER, subscriber.foreign_id)}
|
||||
src={getAvatarSrc(
|
||||
apiUrl,
|
||||
EntityType.SUBSCRIBER,
|
||||
subscriber.foreign_id,
|
||||
)}
|
||||
/>
|
||||
<ConversationHeader.Content>
|
||||
<ChatHeader />
|
||||
@ -118,6 +123,7 @@ export function Chat() {
|
||||
i18n.language,
|
||||
)}`}
|
||||
src={getAvatarSrc(
|
||||
apiUrl,
|
||||
message.sender
|
||||
? EntityType.SUBSCRIBER
|
||||
: EntityType.USER,
|
||||
|
@ -18,12 +18,14 @@ import { Input } from "@/app-components/inputs/Input";
|
||||
import { useFind } from "@/hooks/crud/useFind";
|
||||
import { useUpdate } from "@/hooks/crud/useUpdate";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { EntityType } from "@/services/types";
|
||||
|
||||
import { getAvatarSrc } from "../helpers/mapMessages";
|
||||
import { useChat } from "../hooks/ChatContext";
|
||||
|
||||
export const ChatActions = () => {
|
||||
const { apiUrl } = useConfig();
|
||||
const { t } = useTranslation();
|
||||
const { subscriber: activeChat } = useChat();
|
||||
const [takeoverBy, setTakeoverBy] = useState<string>(
|
||||
@ -57,7 +59,7 @@ export const ChatActions = () => {
|
||||
<Avatar
|
||||
size="sm"
|
||||
name={user.first_name}
|
||||
src={getAvatarSrc(EntityType.USER, user.id)}
|
||||
src={getAvatarSrc(apiUrl, EntityType.USER, user.id)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid>
|
||||
|
@ -16,6 +16,7 @@ import InboxIcon from "@mui/icons-material/MoveToInbox";
|
||||
import { Chip, debounce, Grid } from "@mui/material";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { Title } from "@/layout/content/Title";
|
||||
import { EntityType } from "@/services/types";
|
||||
|
||||
@ -29,6 +30,7 @@ export const SubscribersList = (props: {
|
||||
searchPayload: any;
|
||||
assignedTo: AssignedTo;
|
||||
}) => {
|
||||
const { apiUrl } = useConfig();
|
||||
const { t, i18n } = useTranslation();
|
||||
const chat = useChat();
|
||||
const { fetchNextPage, isFetching, subscribers, hasNextPage } =
|
||||
@ -58,6 +60,7 @@ export const SubscribersList = (props: {
|
||||
>
|
||||
<Avatar
|
||||
src={getAvatarSrc(
|
||||
apiUrl,
|
||||
EntityType.SUBSCRIBER,
|
||||
conversation.foreign_id,
|
||||
)}
|
||||
|
@ -11,7 +11,6 @@ import { Message, MessageModel } from "@chatscope/chat-ui-kit-react";
|
||||
import MenuRoundedIcon from "@mui/icons-material/MenuRounded";
|
||||
import ReplyIcon from "@mui/icons-material/Reply";
|
||||
import { Chip, Grid } from "@mui/material";
|
||||
import getConfig from "next/config";
|
||||
import { ReactNode } from "react";
|
||||
|
||||
import { ROUTES } from "@/services/api.class";
|
||||
@ -21,8 +20,6 @@ import { IMessage, IMessageFull } from "@/types/message.types";
|
||||
import { AttachmentViewer } from "../components/AttachmentViewer";
|
||||
import { Carousel } from "../components/Carousel";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
|
||||
function hasSameSender(
|
||||
m1: IMessage | IMessageFull,
|
||||
m2: IMessage | IMessageFull,
|
||||
@ -133,13 +130,14 @@ export function getMessageContent(
|
||||
* @description Returns the avatar of the subscriber
|
||||
*/
|
||||
export function getAvatarSrc(
|
||||
apiUrl: string,
|
||||
entity: EntityType.USER | EntityType.SUBSCRIBER,
|
||||
id?: string,
|
||||
) {
|
||||
//remove trailing slash
|
||||
return `${String(publicRuntimeConfig.apiUrl).replace(/\/$/, "")}${
|
||||
ROUTES[entity]
|
||||
}/${id || "bot"}/profile_pic`;
|
||||
return `${String(apiUrl).replace(/\/$/, "")}${ROUTES[entity]}/${
|
||||
id || "bot"
|
||||
}/profile_pic`;
|
||||
}
|
||||
|
||||
export function getMessagePosition(
|
||||
@ -186,4 +184,4 @@ export function getMessagePosition(
|
||||
|
||||
// Default case (should not reach here)
|
||||
return "single";
|
||||
}
|
||||
}
|
||||
|
@ -21,7 +21,6 @@ import {
|
||||
MenuItem,
|
||||
} from "@mui/material";
|
||||
import { GridColDef } from "@mui/x-data-grid";
|
||||
import getConfig from "next/config";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@ -38,6 +37,7 @@ import { DataGrid } from "@/app-components/tables/DataGrid";
|
||||
import { useDelete } from "@/hooks/crud/useDelete";
|
||||
import { useFind } from "@/hooks/crud/useFind";
|
||||
import { useGetFromCache } from "@/hooks/crud/useGet";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
|
||||
import { useHasPermission } from "@/hooks/useHasPermission";
|
||||
import { useSearch } from "@/hooks/useSearch";
|
||||
@ -56,7 +56,6 @@ import { buildURL } from "@/utils/URL";
|
||||
import { NlpImportDialog } from "../NlpImportDialog";
|
||||
import { NlpSampleDialog } from "../NlpSampleDialog";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
const NLP_SAMPLE_TYPE_COLORS = {
|
||||
test: "#e6a23c",
|
||||
train: "#67c23a",
|
||||
@ -64,6 +63,7 @@ const NLP_SAMPLE_TYPE_COLORS = {
|
||||
};
|
||||
|
||||
export default function NlpSample() {
|
||||
const { apiUrl } = useConfig();
|
||||
const { toast } = useToast();
|
||||
const { t } = useTranslation();
|
||||
const [dataset, setDataSet] = useState("");
|
||||
@ -287,7 +287,7 @@ export default function NlpSample() {
|
||||
<Button
|
||||
variant="contained"
|
||||
href={buildURL(
|
||||
publicRuntimeConfig.apiUrl,
|
||||
apiUrl,
|
||||
`nlpsample/export${dataset ? `?type=${dataset}` : ""}`,
|
||||
)}
|
||||
startIcon={<DownloadIcon />}
|
||||
|
@ -11,7 +11,6 @@ import { faUsers } from "@fortawesome/free-solid-svg-icons";
|
||||
import PersonAddAlt1Icon from "@mui/icons-material/PersonAddAlt1";
|
||||
import { Button, Grid, Paper } from "@mui/material";
|
||||
import { GridColDef } from "@mui/x-data-grid";
|
||||
import getConfig from "next/config";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ChipEntity } from "@/app-components/displays/ChipEntity";
|
||||
@ -25,6 +24,7 @@ import { buildRenderPicture } from "@/app-components/tables/columns/renderPictur
|
||||
import { DataGrid } from "@/app-components/tables/DataGrid";
|
||||
import { useFind } from "@/hooks/crud/useFind";
|
||||
import { useUpdate } from "@/hooks/crud/useUpdate";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
|
||||
import { useHasPermission } from "@/hooks/useHasPermission";
|
||||
import { useSearch } from "@/hooks/useSearch";
|
||||
@ -39,9 +39,8 @@ import { getDateTimeFormatter } from "@/utils/date";
|
||||
import { EditUserDialog } from "./EditUserDialog";
|
||||
import { InvitationDialog } from "./InvitationDialog";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
|
||||
export const Users = () => {
|
||||
const { ssoEnabled } = useConfig();
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const { mutateAsync: updateUser } = useUpdate(EntityType.USER, {
|
||||
@ -157,7 +156,7 @@ export const Users = () => {
|
||||
},
|
||||
});
|
||||
}}
|
||||
disabled={publicRuntimeConfig.ssoEnabled}
|
||||
disabled={ssoEnabled}
|
||||
>
|
||||
{t(params.row.state ? "label.enabled" : "label.disabled")}
|
||||
</Button>
|
||||
@ -188,7 +187,7 @@ export const Users = () => {
|
||||
valueGetter: (params) =>
|
||||
t("datetime.updated_at", getDateTimeFormatter(params)),
|
||||
},
|
||||
...(!publicRuntimeConfig.ssoEnabled ? [actionColumns] : []),
|
||||
...(!ssoEnabled ? [actionColumns] : []),
|
||||
];
|
||||
|
||||
return (
|
||||
@ -207,7 +206,7 @@ export const Users = () => {
|
||||
<Grid item>
|
||||
<FilterTextfield onChange={onSearch} />
|
||||
</Grid>
|
||||
{!publicRuntimeConfig.ssoEnabled &&
|
||||
{!ssoEnabled &&
|
||||
hasPermission(EntityType.USER, PermissionAction.CREATE) ? (
|
||||
<Grid item>
|
||||
<Button
|
||||
|
@ -8,7 +8,6 @@
|
||||
*/
|
||||
|
||||
import axios from "axios";
|
||||
import getConfig from "next/config";
|
||||
import { stringify } from "qs";
|
||||
import React, { createContext, ReactNode, useContext, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@ -18,17 +17,17 @@ import { EntityType } from "@/services/types";
|
||||
import { IBaseSchema } from "@/types/base.types";
|
||||
|
||||
import { useLogoutRedirection } from "./useAuth";
|
||||
import { useConfig } from "./useConfig";
|
||||
import { useToast } from "./useToast";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
|
||||
export const useAxiosInstance = () => {
|
||||
const { apiUrl } = useConfig();
|
||||
const { logoutRedirection } = useLogoutRedirection();
|
||||
const { toast } = useToast();
|
||||
const { t } = useTranslation();
|
||||
const axiosInstance = useMemo(() => {
|
||||
const instance = axios.create({
|
||||
baseURL: publicRuntimeConfig.apiUrl,
|
||||
baseURL: apiUrl,
|
||||
withCredentials: true,
|
||||
});
|
||||
// Added the same Query String (de)Serializer as NestJS,
|
||||
|
@ -1,13 +1,10 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
|
||||
const ConfigContext = createContext(null);
|
||||
const ConfigContext = createContext<IConfig | null>(null);
|
||||
|
||||
export interface IConfig {
|
||||
NEXT_PUBLIC_API_ORIGIN: string;
|
||||
NEXT_PUBLIC_SSO_ENABLED: boolean;
|
||||
REACT_APP_WIDGET_API_URL: string;
|
||||
REACT_APP_WIDGET_CHANNEL: string;
|
||||
REACT_APP_WIDGET_TOKEN: string;
|
||||
apiUrl: string;
|
||||
ssoEnabled: boolean;
|
||||
}
|
||||
|
||||
export const ConfigProvider = ({ children }) => {
|
||||
|
@ -18,7 +18,6 @@ import {
|
||||
styled,
|
||||
} from "@mui/material";
|
||||
import MuiAppBar, { AppBarProps as MuiAppBarProps } from "@mui/material/AppBar";
|
||||
import getConfig from "next/config";
|
||||
import { FC, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@ -26,12 +25,11 @@ import { HexabotLogo } from "@/app-components/logos/HexabotLogo";
|
||||
import { PopoverMenu } from "@/app-components/menus/PopoverMenu";
|
||||
import { getAvatarSrc } from "@/components/inbox/helpers/mapMessages";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { EntityType } from "@/services/types";
|
||||
|
||||
import { borderLine, theme } from "./themes/theme";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
|
||||
interface AppBarProps extends MuiAppBarProps {
|
||||
open?: boolean;
|
||||
}
|
||||
@ -75,6 +73,7 @@ export type HeaderProps = {
|
||||
onToggleSidebar: () => void;
|
||||
};
|
||||
export const Header: FC<HeaderProps> = ({ isSideBarOpen, onToggleSidebar }) => {
|
||||
const { apiUrl, ssoEnabled } = useConfig();
|
||||
const { t } = useTranslation();
|
||||
const anchorRef = useRef(null);
|
||||
const [isMenuPopoverOpen, setIsMenuPopoverOpen] = useState(false);
|
||||
@ -160,7 +159,7 @@ export const Header: FC<HeaderProps> = ({ isSideBarOpen, onToggleSidebar }) => {
|
||||
</Typography>
|
||||
</Box>
|
||||
<Avatar
|
||||
src={getAvatarSrc(EntityType.USER, user?.id).concat(
|
||||
src={getAvatarSrc(apiUrl, EntityType.USER, user?.id).concat(
|
||||
`?${randomSeed}`,
|
||||
)}
|
||||
color={theme.palette.text.secondary}
|
||||
@ -176,7 +175,7 @@ export const Header: FC<HeaderProps> = ({ isSideBarOpen, onToggleSidebar }) => {
|
||||
last_name: user.last_name,
|
||||
}}
|
||||
links={
|
||||
!publicRuntimeConfig.ssoEnabled
|
||||
!ssoEnabled
|
||||
? [
|
||||
{ text: t("menu.home"), href: "/" },
|
||||
{ text: t("menu.edit_account"), href: "/profile" },
|
||||
|
@ -31,7 +31,6 @@ import SettingsAccessibilityRoundedIcon from "@mui/icons-material/SettingsAccess
|
||||
import { CSSObject, Grid, IconButton, styled, Theme } from "@mui/material";
|
||||
import MuiDrawer from "@mui/material/Drawer";
|
||||
import { OverridableComponent } from "@mui/material/OverridableComponent";
|
||||
import getConfig from "next/config";
|
||||
import { useRouter } from "next/router";
|
||||
import { FC, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@ -39,12 +38,12 @@ import { useTranslation } from "react-i18next";
|
||||
import { HexabotLogo } from "@/app-components/logos/HexabotLogo";
|
||||
import { Sidebar } from "@/app-components/menus/Sidebar";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { useHasPermission } from "@/hooks/useHasPermission";
|
||||
import { EntityType } from "@/services/types";
|
||||
import { PermissionAction } from "@/types/permission.types";
|
||||
import { getLayout } from "@/utils/laylout";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
const drawerWidth = 280;
|
||||
const openedMixin = (theme: Theme): CSSObject => ({
|
||||
width: drawerWidth,
|
||||
@ -107,7 +106,7 @@ export type MenuItem = {
|
||||
submenuItems?: MenuItem[];
|
||||
};
|
||||
|
||||
const MENU_ITEMS: MenuItem[] = [
|
||||
const getMenuItems = (ssoEnabled: boolean): MenuItem[] => [
|
||||
{
|
||||
text: "menu.dashboard",
|
||||
href: "/",
|
||||
@ -236,7 +235,7 @@ const MENU_ITEMS: MenuItem[] = [
|
||||
[EntityType.USER]: [PermissionAction.READ],
|
||||
},
|
||||
},
|
||||
...(!publicRuntimeConfig.ssoEnabled
|
||||
...(!ssoEnabled
|
||||
? [
|
||||
{
|
||||
text: "menu.roles",
|
||||
@ -271,13 +270,15 @@ export const VerticalMenu: FC<VerticalMenuProps> = ({
|
||||
onToggleIn,
|
||||
onToggleOut,
|
||||
}) => {
|
||||
const { ssoEnabled } = useConfig();
|
||||
const { t } = useTranslation();
|
||||
const { isAuthenticated } = useAuth();
|
||||
const router = useRouter();
|
||||
const hasPermission = useHasPermission();
|
||||
const menuItems = getMenuItems(ssoEnabled);
|
||||
// Filter menu item to which user is allowed access
|
||||
const availableMenuItems = useMemo(() => {
|
||||
return MENU_ITEMS.filter(({ requires: requiredPermissions }) => {
|
||||
return menuItems.filter(({ requires: requiredPermissions }) => {
|
||||
return (
|
||||
!requiredPermissions ||
|
||||
Object.entries(requiredPermissions).every((permission) => {
|
||||
|
@ -10,7 +10,7 @@ export default function handler(
|
||||
res: NextApiResponse<ResponseData>,
|
||||
) {
|
||||
res.status(200).json({
|
||||
apiUrl: process.env.NEXT_PUBLIC_API_ORIGIN || "http://localhost:3000",
|
||||
apiUrl: process.env.NEXT_PUBLIC_API_ORIGIN || "http://localhost:4000",
|
||||
ssoEnabled: process.env.NEXT_PUBLIC_SSO_ENABLED === "true" || false,
|
||||
});
|
||||
}
|
||||
|
@ -10,17 +10,16 @@
|
||||
import ChatIcon from "@mui/icons-material/Chat";
|
||||
import { Avatar, Box, Typography } from "@mui/material";
|
||||
import UiChatWidget from "hexabot-widget/src/UiChatWidget";
|
||||
import getConfig from "next/config";
|
||||
import { ReactElement } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { getAvatarSrc } from "@/components/inbox/helpers/mapMessages";
|
||||
import { VisualEditor } from "@/components/visual-editor";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import i18n from "@/i18n/config";
|
||||
import { Layout } from "@/layout";
|
||||
import { EntityType } from "@/services/types";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
const CustomWidgetHeader = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@ -34,12 +33,14 @@ const CustomWidgetHeader = () => {
|
||||
);
|
||||
};
|
||||
const VisualEditorPage = () => {
|
||||
const { apiUrl } = useConfig();
|
||||
|
||||
return (
|
||||
<>
|
||||
<VisualEditor />
|
||||
<UiChatWidget
|
||||
config={{
|
||||
apiUrl: publicRuntimeConfig.apiUrl,
|
||||
apiUrl,
|
||||
channel: "live-chat-tester",
|
||||
token: "test",
|
||||
language: i18n.language,
|
||||
@ -48,7 +49,7 @@ const VisualEditorPage = () => {
|
||||
CustomAvatar={() => (
|
||||
<Avatar
|
||||
sx={{ width: "32px", height: "32px", fontSize: ".75rem" }}
|
||||
src={getAvatarSrc(EntityType.USER, "bot")}
|
||||
src={getAvatarSrc(apiUrl, EntityType.USER, "bot")}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
@ -7,13 +7,10 @@
|
||||
* 3. SaaS Restriction: This software, or any derivative of it, may not be used to offer a competing product or service (SaaS) without prior written consent from Hexastack. Offering the software as a service or using it in a commercial cloud environment without express permission is strictly prohibited.
|
||||
*/
|
||||
|
||||
import getConfig from "next/config";
|
||||
import { io, Socket, ManagerOptions, SocketOptions } from "socket.io-client";
|
||||
|
||||
import { IOIncomingMessage, IOOutgoingMessage } from "./types/io-message";
|
||||
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
|
||||
type SocketIoClientConfig = Partial<ManagerOptions & SocketOptions>;
|
||||
|
||||
export class SocketIoClient {
|
||||
@ -52,13 +49,13 @@ export class SocketIoClient {
|
||||
|
||||
private initialized: boolean = false;
|
||||
|
||||
constructor(socketConfig?: SocketIoClientConfig) {
|
||||
constructor(apiUrl: string, socketConfig?: SocketIoClientConfig) {
|
||||
this.config = {
|
||||
...SocketIoClient.defaultConfig,
|
||||
...socketConfig,
|
||||
autoConnect: false,
|
||||
};
|
||||
const url = new URL(publicRuntimeConfig.apiUrl);
|
||||
const url = new URL(apiUrl);
|
||||
|
||||
this.socket = io(url.origin, this.config);
|
||||
}
|
||||
@ -160,5 +157,3 @@ export class SocketIoClient {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const socketIoClient = new SocketIoClient();
|
||||
|
@ -12,22 +12,24 @@ import {
|
||||
PropsWithChildren,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import { QueryOptions, useQuery } from "react-query";
|
||||
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useConfig } from "@/hooks/useConfig";
|
||||
import { useToast } from "@/hooks/useToast";
|
||||
|
||||
import { SocketIoClient, socketIoClient } from "./SocketIoClient";
|
||||
import { SocketIoClient } from "./SocketIoClient";
|
||||
|
||||
interface socketContext {
|
||||
socket: SocketIoClient;
|
||||
socket: SocketIoClient | null;
|
||||
connected: boolean;
|
||||
}
|
||||
|
||||
const socketContext = createContext<socketContext>({
|
||||
socket: socketIoClient,
|
||||
socket: null,
|
||||
connected: false,
|
||||
});
|
||||
|
||||
@ -36,13 +38,14 @@ export const useSocket = () => {
|
||||
};
|
||||
|
||||
export const SocketProvider = (props: PropsWithChildren) => {
|
||||
const { socket } = useSocket();
|
||||
const { apiUrl } = useConfig();
|
||||
const [connected, setConnected] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const { user } = useAuth();
|
||||
const socket = useMemo(() => new SocketIoClient(apiUrl), [apiUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (user)
|
||||
if (user && apiUrl)
|
||||
socket.init({
|
||||
onConnect: () => {
|
||||
setConnected(true);
|
||||
@ -54,7 +57,7 @@ export const SocketProvider = (props: PropsWithChildren) => {
|
||||
setConnected(false);
|
||||
},
|
||||
});
|
||||
}, [socket, toast, user]);
|
||||
}, [socket, toast, user, apiUrl]);
|
||||
|
||||
return (
|
||||
<socketContext.Provider value={{ socket, connected }}>
|
||||
@ -73,9 +76,9 @@ export const useSubscribe = <T,>(event: string, callback: (arg: T) => void) => {
|
||||
const { socket } = useSocket();
|
||||
|
||||
useEffect(() => {
|
||||
socket.on<T>(event, callback);
|
||||
socket?.on<T>(event, callback);
|
||||
|
||||
return () => socket.off(event, callback);
|
||||
return () => socket?.off(event, callback);
|
||||
}, [event, callback, socket]);
|
||||
};
|
||||
|
||||
@ -83,14 +86,17 @@ export const useSocketGetQuery = <T,>(
|
||||
url: string,
|
||||
options?: Omit<QueryOptions<T, Error, T, string[]>, "queryFn">,
|
||||
) => {
|
||||
const { socket } = useSocket();
|
||||
const query = useQuery({
|
||||
...options,
|
||||
queryKey: ["socket", "get", url],
|
||||
queryFn: async () => {
|
||||
const response = await socketIoClient.get<T>(url);
|
||||
if (!socket) throw new Error("Socket not initialized");
|
||||
const response = await socket.get<T>(url);
|
||||
|
||||
return response.body;
|
||||
},
|
||||
enabled: !!socket,
|
||||
});
|
||||
|
||||
return query;
|
||||
|
Loading…
Reference in New Issue
Block a user