generated from tailored/router-db-template
44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
const isBrowser = (typeof process === 'undefined') ||
|
|
(typeof window !== 'undefined' && typeof window.document !== 'undefined') ||
|
|
(typeof process !== 'undefined' && process?.env?.BROWSER === 'true');
|
|
const chantHttpToWs = (url: string) => {
|
|
if (url.startsWith('http://')) {
|
|
return url.replace('http://', 'ws://');
|
|
}
|
|
if (url.startsWith('https://')) {
|
|
return url.replace('https://', 'wss://');
|
|
}
|
|
return url;
|
|
};
|
|
type WebSocketOptions = {
|
|
/**
|
|
* 是否拒绝不安全的证书, in node only
|
|
*/
|
|
rejectUnauthorized?: boolean;
|
|
headers?: Record<string, string>;
|
|
[key: string]: any;
|
|
};
|
|
export const initWs = async (url: string, options?: WebSocketOptions) => {
|
|
let ws: WebSocket;
|
|
url = chantHttpToWs(url);
|
|
if (isBrowser) {
|
|
ws = new WebSocket(url);
|
|
} else {
|
|
const wsPakcages = 'ws' // 避免vite 自动会默认的在浏览器引入ws然后报错
|
|
const WebSocket = await import(wsPakcages).then((module) => module.default);
|
|
const { rejectUnauthorized, headers, ...rest } = options || {};
|
|
ws = new WebSocket(url, {
|
|
rejectUnauthorized: rejectUnauthorized ?? true,
|
|
headers: headers,
|
|
...rest,
|
|
}) as any;
|
|
}
|
|
return ws;
|
|
};
|
|
export interface EventEmitterOptions {
|
|
/**
|
|
* Enables automatic capturing of promise rejection.
|
|
*/
|
|
captureRejections?: boolean | undefined;
|
|
}
|