Skip to content

Commit

Permalink
Fix/issues (#148)
Browse files Browse the repository at this point in the history
* 🚧 Wip

* 🐛 Fixed issue with logs reconnection
  • Loading branch information
abdheshnayak authored Mar 14, 2024
1 parent 68e89c1 commit 49f42e9
Show file tree
Hide file tree
Showing 15 changed files with 110 additions and 162 deletions.
28 changes: 14 additions & 14 deletions lib/app-setup/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,21 +233,21 @@ const Root = ({
__html: getClientEnv(env),
}}
/>
<LiveReload port={443} />
<Tooltip.Provider>
<ProgressContainer>
<ReloadIndicator />
<NonIdleProgressBar />
{isBrowser() && <ToastContainer position="bottom-left" />}
{error ? (
<div>{JSON.stringify(error)}</div>
) : (
<Wrapper>
{/* <LiveReload port={443} /> */}
<ToastContainer position="bottom-left" />
<ProgressContainer>
<ReloadIndicator />
<NonIdleProgressBar />
{error ? (
<div>{JSON.stringify(error)}</div>
) : (
<Wrapper>
<Tooltip.Provider>
<Outlet />
</Wrapper>
)}
</ProgressContainer>
</Tooltip.Provider>
</Tooltip.Provider>
</Wrapper>
)}
</ProgressContainer>
<Scripts />
</body>
</html>
Expand Down
2 changes: 1 addition & 1 deletion lib/client/helpers/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const logger = {

if (err) {
if (!isDev) {
console.trace(`\n\n${args}\n\n`);
console.trace(`\n\n${err}\n\n`);
return;
}
console.error(`\n\n${err}\n\n`);
Expand Down
79 changes: 33 additions & 46 deletions lib/client/helpers/socket/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
useRef,
useState,
} from 'react';
import * as wsock from 'websocket';
import { ChildrenProps } from '~/components/types';
import ReconnectingWebSocket from 'reconnecting-websocket';
import logger from '~/root/lib/client/helpers/log';
import useDebounce from '~/root/lib/client/hooks/use-debounce';
import { socketUrl } from '~/root/lib/configs/base-url.cjs';
Expand Down Expand Up @@ -152,7 +152,7 @@ export const useSubscribe = <T extends IData>(
};

export const SockProvider = ({ children }: ChildrenProps) => {
const sockPromise = useRef<Promise<wsock.w3cwebsocket> | null>(null);
const sockPromise = useRef<Promise<ReconnectingWebSocket> | null>(null);

const [responses, setResponses] = useState<IResponses>({});
const [errors, setErrors] = useState<IResponses>({});
Expand Down Expand Up @@ -200,7 +200,7 @@ export const SockProvider = ({ children }: ChildrenProps) => {
});
}, []);

const onMessage = useCallback((msg: wsock.IMessageEvent) => {
const onMessage = useCallback((msg: any) => {
try {
const m: ISocketResp = JSON.parse(msg.data as string);

Expand All @@ -223,52 +223,39 @@ export const SockProvider = ({ children }: ChildrenProps) => {
}
}, []);

const getSocket = () => {
return new Promise<ReconnectingWebSocket>((res, rej) => {
try {
// eslint-disable-next-line new-cap
const w = new ReconnectingWebSocket(`${socketUrl}/ws`, '', {});

w.onmessage = onMessage;

w.onopen = () => {
res(w);
};

w.onerror = (e) => {
rej(e);
};

w.onclose = () => {
rej();
};
} catch (e) {
rej(e);
}
});
};

useDebounce(
() => {
if (typeof window !== 'undefined') {
const connnect = (recon = () => {}) => {
try {
sockPromise.current = new Promise<wsock.w3cwebsocket>(
(res, rej) => {
try {
// eslint-disable-next-line new-cap
const w = new wsock.w3cwebsocket(
`${socketUrl}/ws`,
'',
'',
{}
);

w.onmessage = onMessage;

w.onopen = () => {
res(w);
};

w.onerror = (e) => {
console.error(e);
recon();
};

w.onclose = () => {
recon();
};
} catch (e) {
rej(e);
}
}
);
} catch (e) {
logger.error(e);
}
};

connnect(() => {
setTimeout(() => {
console.log('reconnecting');
connnect();
}, 1000);
});
try {
sockPromise.current = getSocket();
} catch (e) {
logger.error(e);
}
}
},
1000,
Expand Down
7 changes: 5 additions & 2 deletions lib/client/hooks/use-custom-loader-data.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@ type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
? I
: never;

export const useExtLoaderData = <T extends (...args: any) => Promise<any>>() =>
useLoaderData() as UnionToIntersection<Awaited<ReturnType<T>>>;
export const useExtLoaderData = <
T extends (...args: any) => Promise<any>
>() => {
return useLoaderData() as UnionToIntersection<Awaited<ReturnType<T>>>;
};
23 changes: 15 additions & 8 deletions lib/server/helpers/execute-query-with-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
NN,
} from '../../types/common';

const ignoreLogsFor = ['accounts_listAccounts', 'auth_me'];

const parseCookie = (cookieString: string) => {
const [cookie] = cookieString.split(';');
const [name, value] = cookie.split('=');
Expand Down Expand Up @@ -43,9 +45,12 @@ export const ExecuteQueryWithContext = (
def?: any
): IExecutorResp<B, C> {
const logId = uuid();
const apiName = `[#${logId.substring(0, 5)}] ${
(q as any)?.definitions[0]?.selectionSet?.selections[0]?.name?.value || ''
}`;

const gqlName =
(q as any)?.definitions[0]?.selectionSet?.selections[0]?.name?.value ||
'';

const apiName = `[#${logId.substring(0, 5)}] ${gqlName}`;

const res: IExecutorResp<B, C> = async (variables) => {
const { transformer } = formatter;
Expand Down Expand Up @@ -111,13 +116,15 @@ export const ExecuteQueryWithContext = (
}
return { ...resp.data, data };
} catch (err) {
if ((err as AxiosError).response) {
console.log('\nErrorIn:', apiName, (err as Error).name, '\n');
if (!ignoreLogsFor.includes(gqlName)) {
if ((err as AxiosError).response) {
console.log('\nErrorIn:', apiName, (err as Error).name, '\n');

return (err as AxiosError).response?.data;
}
return (err as AxiosError).response?.data;
}

console.log('\nErrorIn:', apiName, (err as Error).message, '\n');
console.log('\nErrorIn:', apiName, (err as Error).message, '\n');
}

return {
data: null,
Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@
"react-router-dom": "^6.21.1",
"react-toastify": "^9.1.3",
"react-viewport-list": "^7.1.2",
"reconnecting-websocket": "^4.4.0",
"remix": "^1.19.3",
"search-in-json": "^1.0.67",
"sonner": "^1.4.3",
"swr": "^2.2.4",
"use-immer": "^0.9.0",
"uuid": "^9.0.1",
"websocket": "^1.0.34",
"yup": "^1.3.3"
},
"devDependencies": {
Expand All @@ -115,7 +115,6 @@
"@types/react-dom": "^18.2.18",
"@types/react-ranger": "^2.0.4",
"@types/uuid": "^9.0.7",
"@types/websocket": "^1.0.10",
"@typescript-eslint/eslint-plugin": "^6.17.0",
"@typescript-eslint/parser": "^6.17.0",
"autoprefixer": "^10.4.16",
Expand Down
19 changes: 7 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion src/apps/console/components/loading-component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ const GetSkeleton = ({
};

interface AwaitRespProps {
readonly error?: string;
readonly error?: {
readonly message: string;
};
readonly redirect?: string;
readonly cookie?: FlatMapType<string>[];
}
Expand Down
15 changes: 5 additions & 10 deletions src/apps/console/routes/_a+/teams.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import { redirect } from '@remix-run/node';
import {
Link,
useLoaderData,
useNavigate,
useOutletContext,
} from '@remix-run/react';
import { Link, useNavigate, useOutletContext } from '@remix-run/react';
import { useEffect, useState } from 'react';
import { Button } from '~/components/atoms/button';
import { usePagination } from '~/components/molecule/pagination';
import { cn, generateKey } from '~/components/utils';
import logger from '~/root/lib/client/helpers/log';
import { authBaseUrl } from '~/root/lib/configs/base-url.cjs';
import { UserMe } from '~/root/lib/server/gql/saved-queries';
import { IRemixCtx } from '~/root/lib/types/common';
Expand All @@ -26,6 +20,7 @@ import ConsoleAvatar from '~/console/components/console-avatar';
import { ArrowRight, Users } from '~/console/components/icons';
import SplitWrapper from '~/console/components/split-wrapper';
import FillerTeam from '~/console/assets/filler-team';
import { useExtLoaderData } from '~/root/lib/client/hooks/use-custom-loader-data';

export const loader = async (ctx: IRemixCtx) => {
let accounts;
Expand All @@ -35,7 +30,7 @@ export const loader = async (ctx: IRemixCtx) => {
{}
);
if (errors) {
throw errors[0];
return handleError(errors[0]);
}
accounts = data;

Expand All @@ -58,7 +53,7 @@ export const loader = async (ctx: IRemixCtx) => {
};
}
} catch (err) {
logger.error(err);
return handleError(err);
}
return {
accounts: accounts || [],
Expand All @@ -67,7 +62,7 @@ export const loader = async (ctx: IRemixCtx) => {
};

const Accounts = () => {
const { accounts, invites } = useLoaderData<typeof loader>();
const { accounts, invites } = useExtLoaderData<typeof loader>();
const { user } = useOutletContext<{
user: UserMe;
}>();
Expand Down
Loading

0 comments on commit 49f42e9

Please sign in to comment.