UNPKG

@blocklet/ui-react

Version:

Some useful front-end web components that can be used in Blocklets.

39 lines (31 loc) 1.04 kB
import { use } from 'react'; import { WsClient } from '@arcblock/ws'; import { SessionContext } from '@arcblock/did-connect/lib/Session'; import { joinURL } from 'ufo'; import { BLOCKLET_SERVICE_PATH_PREFIX } from '@arcblock/ux/lib/Util/constant'; const client = {}; export function create(endpoint = 'admin') { let pathPrefix = '/'; if (!window?.blocklet && window?.env?.apiPrefix) { pathPrefix = window.env.apiPrefix; } const url = joinURL(pathPrefix, BLOCKLET_SERVICE_PATH_PREFIX, endpoint); return new WsClient(url, { heartbeatIntervalMs: 100 * 1000, }); } export default function getWsClient(endpoint = 'admin') { if (!client[endpoint]) { client[endpoint] = create(endpoint); } return client[endpoint]; } export const useListenWsClient = (endpoint = 'admin') => { const sessionCtx = use(SessionContext); const { session } = sessionCtx ?? {}; if (!client[endpoint] && session.user) { client[endpoint] = getWsClient(endpoint); client[endpoint].connect(); } return client[endpoint]; };