Compare commits
14 Commits
64b37e369d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b53968df8b | |||
| ca154ba883 | |||
| 14dec5f5c5 | |||
| 452f821d06 | |||
| 27adb05c39 | |||
| 66905f13a9 | |||
| 366840bb1d | |||
| 8385ab05f6 | |||
| 515c6e6cf7 | |||
| 1104efaa1a | |||
| cf6ca31aa4 | |||
| 320bc93c69 | |||
| 0570acb78f | |||
| fd5437292a |
@@ -1,4 +1,5 @@
|
|||||||
import { QueryClient } from '@abearxiong/query';
|
// @ts-ignore
|
||||||
|
import { QueryClient } from '@kevisual/query';
|
||||||
|
|
||||||
const query = new QueryClient({ url: '/api/router', io: true });
|
const query = new QueryClient({ url: '/api/router', io: true });
|
||||||
|
|
||||||
|
|||||||
13
package.json
13
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@kevisual/query",
|
"name": "@kevisual/query",
|
||||||
"version": "0.0.14",
|
"version": "0.0.29",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"module": "dist/index.js",
|
"module": "dist/index.js",
|
||||||
"types": "dist/index.d.ts",
|
"types": "dist/index.d.ts",
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "npm run clean && rollup -c",
|
"build": "npm run clean && rollup -c",
|
||||||
"build:app": "npm run build && rsync dist/* ../deploy/dist",
|
"build:app": "npm run build && rsync dist/* ../deploy/dist",
|
||||||
|
"dev:lib": "rollup -c -w",
|
||||||
"clean": "rm -rf dist"
|
"clean": "rm -rf dist"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
@@ -24,12 +25,12 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rollup/plugin-node-resolve": "^16.0.1",
|
"@rollup/plugin-node-resolve": "^16.0.1",
|
||||||
"@rollup/plugin-typescript": "^12.1.2",
|
"@rollup/plugin-typescript": "^12.1.2",
|
||||||
"rollup": "^4.36.0",
|
"rollup": "^4.41.1",
|
||||||
"rollup-plugin-dts": "^6.2.0",
|
"rollup-plugin-dts": "^6.2.1",
|
||||||
"ts-node": "^10.9.2",
|
"ts-node": "^10.9.2",
|
||||||
"tslib": "^2.8.1",
|
"tslib": "^2.8.1",
|
||||||
"typescript": "^5.8.2",
|
"typescript": "^5.8.3",
|
||||||
"zustand": "^5.0.3"
|
"zustand": "^5.0.5"
|
||||||
},
|
},
|
||||||
"packageManager": "yarn@1.22.22",
|
"packageManager": "yarn@1.22.22",
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
@@ -58,6 +59,6 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"openai": "^4.88.0"
|
"openai": "^5.0.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
22
readme.md
22
readme.md
@@ -1,6 +1,6 @@
|
|||||||
# query
|
# query
|
||||||
|
|
||||||
对应的 fetch 内容的一部分功能的封装。
|
对 fetch 功能的的一部分功能的封装。主要处理header的token的提交和response中的处理json。
|
||||||
|
|
||||||
主要目的:请求路径默认`/api/router`,使用`post`,`post`的数据分流使用`path`和`key`.
|
主要目的:请求路径默认`/api/router`,使用`post`,`post`的数据分流使用`path`和`key`.
|
||||||
|
|
||||||
@@ -8,7 +8,6 @@
|
|||||||
|
|
||||||
## query
|
## query
|
||||||
|
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const query = new Query();
|
const query = new Query();
|
||||||
const res = await query.post({
|
const res = await query.post({
|
||||||
@@ -35,4 +34,21 @@ type Data = {
|
|||||||
type DataOpts = Partial<QueryOpts> & {
|
type DataOpts = Partial<QueryOpts> & {
|
||||||
beforeRequest?: Fn;
|
beforeRequest?: Fn;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 适配的@kevisual/router的代码
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { App } from '@kevisual/router';
|
||||||
|
const app = new App();
|
||||||
|
|
||||||
|
app
|
||||||
|
.route({
|
||||||
|
path: 'demo',
|
||||||
|
key: '1',
|
||||||
|
})
|
||||||
|
.define(async (ctx) => {
|
||||||
|
ctx.body = 234;
|
||||||
|
})
|
||||||
|
.addTo(app);
|
||||||
|
```
|
||||||
|
|||||||
@@ -1,50 +1,89 @@
|
|||||||
export const methods = ['GET', 'POST'] as const;
|
export const methods = ['GET', 'POST'] as const;
|
||||||
export type Method = (typeof methods)[number];
|
export type Method = (typeof methods)[number];
|
||||||
|
|
||||||
|
type SimpleObject = Record<string, any>;
|
||||||
export type AdapterOpts = {
|
export type AdapterOpts = {
|
||||||
url: string;
|
url?: string;
|
||||||
headers?: Record<string, string>;
|
headers?: Record<string, string>;
|
||||||
body?: Record<string, any>;
|
body?: Record<string, any> | FormData; // body 可以是对象、字符串或 FormData
|
||||||
timeout?: number;
|
timeout?: number;
|
||||||
method?: Method;
|
method?: Method;
|
||||||
|
isBlob?: boolean; // 是否返回 Blob 对象, 第一优先
|
||||||
|
isText?: boolean; // 是否返回文本内容, 第二优先
|
||||||
|
isPostFile?: boolean; // 是否为文件上传
|
||||||
|
};
|
||||||
|
export const isTextForContentType = (contentType: string | null) => {
|
||||||
|
if (!contentType) return false;
|
||||||
|
const textTypes = ['text/', 'xml', 'html', 'javascript', 'css', 'csv', 'plain', 'x-www-form-urlencoded'];
|
||||||
|
return textTypes.some((type) => contentType.includes(type));
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param opts
|
* @param opts
|
||||||
* @param overloadOpts 覆盖fetch的默认配置
|
* @param overloadOpts 覆盖fetch的默认配置
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const adapter = async (opts: AdapterOpts, overloadOpts?: RequestInit) => {
|
export const adapter = async (opts: AdapterOpts = {}, overloadOpts?: RequestInit) => {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const signal = controller.signal;
|
const signal = controller.signal;
|
||||||
|
const isBlob = opts.isBlob || false; // 是否返回 Blob 对象
|
||||||
|
const isText = opts.isText || false; // 是否返回文本内容
|
||||||
|
const isPostFile = opts.isPostFile || false; // 是否为文件上传
|
||||||
const timeout = opts.timeout || 60000 * 3; // 默认超时时间为 60s * 3
|
const timeout = opts.timeout || 60000 * 3; // 默认超时时间为 60s * 3
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
controller.abort();
|
controller.abort();
|
||||||
}, timeout);
|
}, timeout);
|
||||||
let method = overloadOpts?.method || opts.method || 'POST';
|
let method = overloadOpts?.method || opts?.method || 'POST';
|
||||||
let url = new URL(opts.url, window.location.origin);
|
let headers = { ...opts?.headers, ...overloadOpts?.headers };
|
||||||
|
let origin = '';
|
||||||
|
let url: URL;
|
||||||
|
if (opts?.url?.startsWith('http')) {
|
||||||
|
url = new URL(opts.url);
|
||||||
|
} else {
|
||||||
|
origin = window?.location?.origin || 'http://localhost:51015';
|
||||||
|
url = new URL(opts.url, origin);
|
||||||
|
}
|
||||||
const isGet = method === 'GET';
|
const isGet = method === 'GET';
|
||||||
if (isGet) {
|
if (isGet) {
|
||||||
url.search = new URLSearchParams(opts.body).toString();
|
url.search = new URLSearchParams(opts.body as SimpleObject).toString();
|
||||||
|
}
|
||||||
|
let body: string | FormData | undefined = undefined;
|
||||||
|
if (isGet) {
|
||||||
|
body = undefined;
|
||||||
|
} else if (isPostFile) {
|
||||||
|
body = opts.body as FormData; // 如果是文件上传,直接使用 FormData
|
||||||
|
} else {
|
||||||
|
headers = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...headers,
|
||||||
|
};
|
||||||
|
body = JSON.stringify(opts.body); // 否则将对象转换为 JSON 字符串
|
||||||
}
|
}
|
||||||
return fetch(url, {
|
return fetch(url, {
|
||||||
method: method.toUpperCase(),
|
method: method.toUpperCase(),
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...opts.headers,
|
|
||||||
},
|
|
||||||
signal,
|
signal,
|
||||||
|
body: body,
|
||||||
...overloadOpts,
|
...overloadOpts,
|
||||||
body: isGet ? undefined : JSON.stringify(opts.body),
|
headers: headers,
|
||||||
})
|
})
|
||||||
.then((response) => {
|
.then(async (response) => {
|
||||||
// 获取 Content-Type 头部信息
|
// 获取 Content-Type 头部信息
|
||||||
const contentType = response.headers.get('Content-Type');
|
const contentType = response.headers.get('Content-Type');
|
||||||
|
if (isBlob) {
|
||||||
|
return await response.blob(); // 直接返回 Blob 对象
|
||||||
|
}
|
||||||
|
const isJson = contentType && contentType.includes('application/json');
|
||||||
// 判断返回的数据类型
|
// 判断返回的数据类型
|
||||||
if (contentType && contentType.includes('application/json')) {
|
if (isJson && !isText) {
|
||||||
return response.json(); // 解析为 JSON
|
return await response.json(); // 解析为 JSON
|
||||||
|
} else if (isTextForContentType(contentType)) {
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
status: response.status,
|
||||||
|
data: await response.text(), // 直接返回文本内容
|
||||||
|
};
|
||||||
} else {
|
} else {
|
||||||
return response.text(); // 解析为文本
|
return response;
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { adapter } from './adapter.ts';
|
import { adapter } from './adapter.ts';
|
||||||
import { QueryWs, QueryWsOpts } from './ws.ts';
|
import { QueryWs, QueryWsOpts } from './ws.ts';
|
||||||
import { Query } from './query.ts';
|
import { Query, ClientQuery } from './query.ts';
|
||||||
|
import { BaseQuery, wrapperError } from './query.ts';
|
||||||
|
|
||||||
export { QueryOpts, QueryWs, Query, QueryWsOpts, adapter };
|
export { QueryOpts, QueryWs, ClientQuery, Query, QueryWsOpts, adapter, BaseQuery, wrapperError };
|
||||||
|
|
||||||
|
export type { DataOpts, Result, Data } from './query.ts';
|
||||||
|
|
||||||
type QueryOpts = {
|
type QueryOpts = {
|
||||||
url?: string;
|
url?: string;
|
||||||
@@ -12,14 +15,12 @@ type QueryOpts = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 前端调用后端QueryRouter
|
* 前端调用后端QueryRouter, 封装 beforeRequest 和 wss
|
||||||
*/
|
*/
|
||||||
export class QueryClient extends Query {
|
export class QueryClient extends Query {
|
||||||
tokenName: string;
|
tokenName: string;
|
||||||
storage: Storage;
|
storage: Storage;
|
||||||
token: string;
|
token: string;
|
||||||
// 默认不使用ws
|
|
||||||
qws: QueryWs;
|
|
||||||
constructor(opts?: QueryOpts & { tokenName?: string; storage?: Storage; io?: boolean }) {
|
constructor(opts?: QueryOpts & { tokenName?: string; storage?: Storage; io?: boolean }) {
|
||||||
super(opts);
|
super(opts);
|
||||||
this.tokenName = opts?.tokenName || 'token';
|
this.tokenName = opts?.tokenName || 'token';
|
||||||
|
|||||||
114
src/query.ts
114
src/query.ts
@@ -1,4 +1,5 @@
|
|||||||
import { adapter, Method } from './adapter.ts';
|
import { adapter, isTextForContentType, Method, AdapterOpts } from './adapter.ts';
|
||||||
|
import type { QueryWs } from './ws.ts';
|
||||||
/**
|
/**
|
||||||
* 请求前处理函数
|
* 请求前处理函数
|
||||||
* @param opts 请求配置
|
* @param opts 请求配置
|
||||||
@@ -10,16 +11,12 @@ export type Fn = (opts: {
|
|||||||
body?: Record<string, any>;
|
body?: Record<string, any>;
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
timeout?: number;
|
timeout?: number;
|
||||||
}) => Promise<Record<string, any>>;
|
}) => Promise<Record<string, any> | false>;
|
||||||
|
|
||||||
export type QueryOpts = {
|
export type QueryOpts = {
|
||||||
url?: string;
|
|
||||||
adapter?: typeof adapter;
|
adapter?: typeof adapter;
|
||||||
headers?: Record<string, string>;
|
|
||||||
timeout?: number;
|
|
||||||
method?: Method;
|
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
};
|
} & AdapterOpts;
|
||||||
export type Data = {
|
export type Data = {
|
||||||
path?: string;
|
path?: string;
|
||||||
key?: string;
|
key?: string;
|
||||||
@@ -47,6 +44,10 @@ export type Result<S = any> = {
|
|||||||
export type DataOpts = Partial<QueryOpts> & {
|
export type DataOpts = Partial<QueryOpts> & {
|
||||||
beforeRequest?: Fn;
|
beforeRequest?: Fn;
|
||||||
afterResponse?: <S = any>(result: Result<S>, ctx?: { req?: any; res?: any; fetch?: any }) => Promise<Result<S>>;
|
afterResponse?: <S = any>(result: Result<S>, ctx?: { req?: any; res?: any; fetch?: any }) => Promise<Result<S>>;
|
||||||
|
/**
|
||||||
|
* 是否在stop的时候不请求
|
||||||
|
*/
|
||||||
|
noStop?: boolean;
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* 设置基础响应, 设置 success 和 showError,
|
* 设置基础响应, 设置 success 和 showError,
|
||||||
@@ -54,7 +55,7 @@ export type DataOpts = Partial<QueryOpts> & {
|
|||||||
* showError 是 如果 success 为 false 且 noMsg 为 false, 则调用 showError
|
* showError 是 如果 success 为 false 且 noMsg 为 false, 则调用 showError
|
||||||
* @param res 响应
|
* @param res 响应
|
||||||
*/
|
*/
|
||||||
export const setBaseResponse = (res: Result) => {
|
export const setBaseResponse = (res: Partial<Result>) => {
|
||||||
res.success = res.code === 200;
|
res.success = res.code === 200;
|
||||||
/**
|
/**
|
||||||
* 显示错误
|
* 显示错误
|
||||||
@@ -65,6 +66,19 @@ export const setBaseResponse = (res: Result) => {
|
|||||||
fn?.();
|
fn?.();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
return res as Result;
|
||||||
|
};
|
||||||
|
export const wrapperError = ({ code, message }: { code?: number; message?: string }) => {
|
||||||
|
const result = {
|
||||||
|
code: code || 500,
|
||||||
|
success: false,
|
||||||
|
message: message || 'api request error',
|
||||||
|
showError: (fn?: () => void) => {
|
||||||
|
//
|
||||||
|
},
|
||||||
|
noMsg: true,
|
||||||
|
};
|
||||||
|
return result;
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* const query = new Query();
|
* const query = new Query();
|
||||||
@@ -86,6 +100,8 @@ export class Query {
|
|||||||
* 需要突然停止请求,比如401的时候
|
* 需要突然停止请求,比如401的时候
|
||||||
*/
|
*/
|
||||||
stop?: boolean;
|
stop?: boolean;
|
||||||
|
// 默认不使用ws
|
||||||
|
qws: QueryWs;
|
||||||
|
|
||||||
constructor(opts?: QueryOpts) {
|
constructor(opts?: QueryOpts) {
|
||||||
this.adapter = opts?.adapter || adapter;
|
this.adapter = opts?.adapter || adapter;
|
||||||
@@ -95,6 +111,9 @@ export class Query {
|
|||||||
};
|
};
|
||||||
this.timeout = opts?.timeout || 60000 * 3; // 默认超时时间为 60s * 3
|
this.timeout = opts?.timeout || 60000 * 3; // 默认超时时间为 60s * 3
|
||||||
}
|
}
|
||||||
|
setQueryWs(qws: QueryWs) {
|
||||||
|
this.qws = qws;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 突然停止请求
|
* 突然停止请求
|
||||||
*/
|
*/
|
||||||
@@ -137,18 +156,26 @@ export class Query {
|
|||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
if (_beforeRequest) {
|
if (_beforeRequest) {
|
||||||
await _beforeRequest(req);
|
const res = await _beforeRequest(req);
|
||||||
|
if (res === false) {
|
||||||
|
return wrapperError({
|
||||||
|
code: 500,
|
||||||
|
message: 'request is cancel',
|
||||||
|
// @ts-ignore
|
||||||
|
req: req,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('request beforeFn error', e, req);
|
console.error('request beforeFn error', e, req);
|
||||||
return {
|
return wrapperError({
|
||||||
code: 500,
|
code: 500,
|
||||||
success: false,
|
|
||||||
message: 'api request beforeFn error',
|
message: 'api request beforeFn error',
|
||||||
showError: () => {},
|
// @ts-ignore
|
||||||
};
|
req: req,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (this.stop) {
|
if (this.stop && !options?.noStop) {
|
||||||
const that = this;
|
const that = this;
|
||||||
await new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
let timer = 0;
|
let timer = 0;
|
||||||
@@ -177,13 +204,13 @@ export class Query {
|
|||||||
|
|
||||||
return res;
|
return res;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('request error', e, req);
|
console.error('request afterFn error', e, req);
|
||||||
return {
|
return wrapperError({
|
||||||
code: 500,
|
code: 500,
|
||||||
success: false,
|
|
||||||
message: 'api request afterFn error',
|
message: 'api request afterFn error',
|
||||||
showError: () => {},
|
// @ts-ignore
|
||||||
};
|
req: req,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -201,6 +228,55 @@ export class Query {
|
|||||||
after(fn: DataOpts['afterResponse']) {
|
after(fn: DataOpts['afterResponse']) {
|
||||||
this.afterResponse = fn;
|
this.afterResponse = fn;
|
||||||
}
|
}
|
||||||
|
async fetchText(urlOrOptions?: string | QueryOpts, options?: QueryOpts): Promise<Result<any>> {
|
||||||
|
let _options = { ...options };
|
||||||
|
if (typeof urlOrOptions === 'string' && !_options.url) {
|
||||||
|
_options.url = urlOrOptions;
|
||||||
|
}
|
||||||
|
if (typeof urlOrOptions === 'object') {
|
||||||
|
_options = { ...urlOrOptions, ..._options };
|
||||||
|
}
|
||||||
|
const res = await adapter({
|
||||||
|
method: 'GET',
|
||||||
|
..._options,
|
||||||
|
headers: {
|
||||||
|
...this.headers,
|
||||||
|
...(_options?.headers || {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return setBaseResponse(res);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export { adapter };
|
export { adapter };
|
||||||
|
|
||||||
|
export class BaseQuery<T extends Query = Query, R extends { queryChain?: any; query?: any } = { queryChain: any; query?: T }> {
|
||||||
|
query: T;
|
||||||
|
queryDefine: R;
|
||||||
|
constructor(opts?: { query?: T; queryDefine?: R; clientQuery?: T }) {
|
||||||
|
if (opts?.clientQuery) {
|
||||||
|
this.query = opts.clientQuery;
|
||||||
|
} else {
|
||||||
|
this.query = opts?.query;
|
||||||
|
}
|
||||||
|
if (opts.queryDefine) {
|
||||||
|
this.queryDefine = opts.queryDefine;
|
||||||
|
this.queryDefine.query = this.query;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get chain(): R['queryChain'] {
|
||||||
|
return this.queryDefine.queryChain;
|
||||||
|
}
|
||||||
|
post<R = any, P = any>(data: P, options?: DataOpts): Promise<Result<R>> {
|
||||||
|
return this.query.post(data, options);
|
||||||
|
}
|
||||||
|
get<R = any, P = any>(data: P, options?: DataOpts): Promise<Result<R>> {
|
||||||
|
return this.query.get(data, options);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ClientQuery extends Query {
|
||||||
|
constructor(opts?: QueryOpts) {
|
||||||
|
super({ ...opts, url: opts?.url || '/client/router' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
77
src/ws.ts
77
src/ws.ts
@@ -47,31 +47,42 @@ export class QueryWs {
|
|||||||
*/
|
*/
|
||||||
async connect(opts?: { timeout?: number }) {
|
async connect(opts?: { timeout?: number }) {
|
||||||
const store = this.store;
|
const store = this.store;
|
||||||
|
const that = this;
|
||||||
const connected = store.getState().connected;
|
const connected = store.getState().connected;
|
||||||
if (connected) {
|
if (connected) {
|
||||||
return Promise.resolve(true);
|
return Promise.resolve(true);
|
||||||
}
|
}
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const ws = this.ws || new WebSocket(this.url);
|
const ws = that.ws || new WebSocket(that.url);
|
||||||
const timeout = opts?.timeout || 5 * 60 * 1000; // 默认 2 分钟
|
const timeout = opts?.timeout || 5 * 60 * 1000; // 默认 5 分钟
|
||||||
let timer = setTimeout(() => {
|
let timer = setTimeout(() => {
|
||||||
console.error('WebSocket 连接超时');
|
const isOpen = ws.readyState === WebSocket.OPEN;
|
||||||
reject('timeout');
|
if (isOpen) {
|
||||||
|
console.log('WebSocket 连接成功 in timer');
|
||||||
|
resolve(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('WebSocket 连接超时', that.url);
|
||||||
|
resolve(false);
|
||||||
}, timeout);
|
}, timeout);
|
||||||
ws.onopen = () => {
|
ws.onopen = (ev) => {
|
||||||
store.getState().setConnected(true);
|
store.getState().setConnected(true);
|
||||||
store.getState().setStatus('connected');
|
store.getState().setStatus('connected');
|
||||||
resolve(true);
|
resolve(true);
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
};
|
};
|
||||||
ws.onclose = () => {
|
ws.onclose = (ev) => {
|
||||||
store.getState().setConnected(false);
|
store.getState().setConnected(false);
|
||||||
store.getState().setStatus('disconnected');
|
store.getState().setStatus('disconnected');
|
||||||
this.ws = null;
|
this.ws = null;
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* ws.onopen 必须用这个去获取,否者会丢失链接信息
|
||||||
|
* @param callback
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
listenConnect(callback: () => void) {
|
listenConnect(callback: () => void) {
|
||||||
const store = this.store;
|
const store = this.store;
|
||||||
const { connected } = store.getState();
|
const { connected } = store.getState();
|
||||||
@@ -96,10 +107,41 @@ export class QueryWs {
|
|||||||
);
|
);
|
||||||
return cancel;
|
return cancel;
|
||||||
}
|
}
|
||||||
|
listenClose(callback: () => void) {
|
||||||
|
const store = this.store;
|
||||||
|
const { status } = store.getState();
|
||||||
|
if (status === 'disconnected') {
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
const subscriptionOne = (selector: (state: QueryWsStore) => QueryWsStore['status'], listener: QueryWsStoreListener) => {
|
||||||
|
const unsubscribe = store.subscribe((newState: any, oldState: any) => {
|
||||||
|
if (selector(newState) !== selector(oldState)) {
|
||||||
|
listener(newState, oldState);
|
||||||
|
unsubscribe();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return unsubscribe;
|
||||||
|
};
|
||||||
|
const cancel = subscriptionOne(
|
||||||
|
(state) => state.status,
|
||||||
|
(newState, oldState) => {
|
||||||
|
if (newState.status === 'disconnected') {
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return cancel;
|
||||||
|
}
|
||||||
onMessage<T = any, U = any>(
|
onMessage<T = any, U = any>(
|
||||||
fn: (data: U, event: MessageEvent) => void,
|
fn: (data: U, event: MessageEvent) => void,
|
||||||
opts?: {
|
opts?: {
|
||||||
|
/**
|
||||||
|
* 是否将数据转换为 JSON
|
||||||
|
*/
|
||||||
isJson?: boolean;
|
isJson?: boolean;
|
||||||
|
/**
|
||||||
|
* 选择器
|
||||||
|
*/
|
||||||
selector?: (data: T) => U;
|
selector?: (data: T) => U;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
@@ -136,7 +178,26 @@ export class QueryWs {
|
|||||||
store.getState().setConnected(false);
|
store.getState().setConnected(false);
|
||||||
store.getState().setStatus('disconnected');
|
store.getState().setStatus('disconnected');
|
||||||
}
|
}
|
||||||
send<T = any, U = any>(data: T, opts?: { isJson?: boolean; wrapper?: (data: T) => U }) {
|
/**
|
||||||
|
* 发送消息
|
||||||
|
*
|
||||||
|
* @param data
|
||||||
|
* @param opts
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
send<T = any, U = any>(
|
||||||
|
data: T,
|
||||||
|
opts?: {
|
||||||
|
/**
|
||||||
|
* 是否将数据转换为 JSON
|
||||||
|
*/
|
||||||
|
isJson?: boolean;
|
||||||
|
/**
|
||||||
|
* 包装数据
|
||||||
|
*/
|
||||||
|
wrapper?: (data: T) => U;
|
||||||
|
},
|
||||||
|
) {
|
||||||
const ws = this.ws;
|
const ws = this.ws;
|
||||||
const isJson = opts?.isJson ?? true;
|
const isJson = opts?.isJson ?? true;
|
||||||
const wrapper = opts?.wrapper;
|
const wrapper = opts?.wrapper;
|
||||||
|
|||||||
Reference in New Issue
Block a user