add better access control
This commit is contained in:
@@ -1,20 +1,34 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { use, useEffect, useMemo, useState } from 'react';
|
||||
import { useAuth } from '@clerk/nextjs';
|
||||
import useWebSocket from 'react-use-websocket';
|
||||
|
||||
import { getSuperJson } from '@openpanel/common';
|
||||
|
||||
export default function useWS<T>(path: string, onMessage: (event: T) => void) {
|
||||
const auth = useAuth();
|
||||
const ws = String(process.env.NEXT_PUBLIC_API_URL)
|
||||
.replace(/^https/, 'wss')
|
||||
.replace(/^http/, 'ws');
|
||||
const [socketUrl, setSocketUrl] = useState(`${ws}${path}`);
|
||||
const [baseUrl, setBaseUrl] = useState(`${ws}${path}`);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const socketUrl = useMemo(
|
||||
() => (token ? `${baseUrl}?token=${token}` : baseUrl),
|
||||
[baseUrl, token]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (socketUrl === `${ws}${path}`) return;
|
||||
setSocketUrl(`${ws}${path}`);
|
||||
}, [path, socketUrl, ws]);
|
||||
if (auth.isSignedIn) {
|
||||
auth.getToken().then(setToken);
|
||||
}
|
||||
}, [auth]);
|
||||
|
||||
useEffect(() => {
|
||||
if (baseUrl === `${ws}${path}`) return;
|
||||
setBaseUrl(`${ws}${path}`);
|
||||
}, [path, baseUrl, ws]);
|
||||
console.log('socketUrl', socketUrl);
|
||||
|
||||
useWebSocket(socketUrl, {
|
||||
shouldReconnect: () => true,
|
||||
|
||||
Reference in New Issue
Block a user