From b3b88968a61d691fdd643a4fd426a79979578128 Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Fri, 2 Jul 2021 22:57:04 +0800 Subject: [PATCH] =?UTF-8?q?refactor(web):=20=E7=99=BB=E5=BD=95=E6=88=90?= =?UTF-8?q?=E5=8A=9F=E5=90=8E=E8=BF=9E=E6=8E=A5=E5=88=B0=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/api/socket.ts | 32 ++++++++++++++++++++++++++++++++ shared/index.tsx | 1 + web/src/hooks/useEnsureSocket.ts | 17 +++++++++++++++++ web/src/routes/Entry/index.tsx | 2 +- web/src/routes/Main.tsx | 12 ++++++++++++ 5 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 web/src/hooks/useEnsureSocket.ts diff --git a/shared/api/socket.ts b/shared/api/socket.ts index e69de29b..b3a2a65b 100644 --- a/shared/api/socket.ts +++ b/shared/api/socket.ts @@ -0,0 +1,32 @@ +import { io, Socket } from 'socket.io-client'; +import { config } from '../config'; +import _isNil from 'lodash/isNil'; + +let socket: Socket; + +/** + * 创建Socket连接 + * 如果已经有Socket连接则关闭上一个 + * @param token Token + */ +export function createSocket(token: string) { + if (!_isNil(socket)) { + socket.close(); + } + + return new Promise((resolve, reject) => { + socket = io(config.serverUrl, { + transports: ['websocket'], + auth: { + token, + }, + }); + socket.once('connect', () => { + // 连接成功 + resolve(); + }); + socket.once('error', () => { + reject(); + }); + }); +} diff --git a/shared/index.tsx b/shared/index.tsx index 9f476bf1..9d5a9ada 100644 --- a/shared/index.tsx +++ b/shared/index.tsx @@ -1,5 +1,6 @@ // api export { buildStorage } from './api/buildStorage'; +export { createSocket } from './api/socket'; // components export { FastForm } from './components/FastForm/index'; diff --git a/web/src/hooks/useEnsureSocket.ts b/web/src/hooks/useEnsureSocket.ts new file mode 100644 index 00000000..0833a78c --- /dev/null +++ b/web/src/hooks/useEnsureSocket.ts @@ -0,0 +1,17 @@ +import { createSocket, useAsync } from 'pawchat-shared'; +import { getUserJWT } from '../utils/jwt-helper'; + +/** + * 创建全局Socket + */ +export function useEnsureSocket() { + const { loading, error } = useAsync(async () => { + const token = await getUserJWT(); + if (typeof token === 'string') { + await createSocket(token); + console.log('当前socket连接成功'); // TODO + } + }, []); + + return { loading, error }; +} diff --git a/web/src/routes/Entry/index.tsx b/web/src/routes/Entry/index.tsx index 834807f5..6af63917 100644 --- a/web/src/routes/Entry/index.tsx +++ b/web/src/routes/Entry/index.tsx @@ -9,7 +9,7 @@ import { RegisterView } from './RegisterView'; export const EntryRoute = React.memo(() => { return ( -
+
{ + const { loading } = useEnsureSocket(); + + if (loading) { + return ( +
+ +
+ ); + } + return (