feat: 添加queryclient

This commit is contained in:
xion 2024-09-28 22:22:17 +08:00
parent 61a68fbd41
commit 742a562109
2 changed files with 39 additions and 1 deletions

View File

@ -1,5 +1,6 @@
import { adapter } from './adapter.ts'; import { adapter } from './adapter.ts';
export { QueryWs } from './ws.ts'; import { QueryWs } from './ws.ts';
export { QueryOpts };
type Fn = (opts: { type Fn = (opts: {
url?: string; url?: string;
headers?: Record<string, string>; headers?: Record<string, string>;
@ -37,6 +38,8 @@ type DataOpts = Partial<QueryOpts> & {
* path: 'demo', * path: 'demo',
* key: '1', * key: '1',
* }); * });
*
* U是参数 V是返回值
*/ */
export class Query<U = any, V = any> { export class Query<U = any, V = any> {
adapter: typeof adapter; adapter: typeof adapter;
@ -86,5 +89,39 @@ export class Query<U = any, V = any> {
this.afterResponse = fn; this.afterResponse = fn;
} }
} }
/**
* QueryRouter
*/
export class QueryClient<U = any, V = any> extends Query<U, V> {
tokenName: string;
storage: Storage;
token: string;
qws: QueryWs;
constructor(opts?: QueryOpts & { tokenName?: string; storage?: Storage }) {
super(opts);
this.tokenName = opts?.tokenName || 'token';
this.storage = opts?.storage || localStorage;
this.beforeRequest = async (opts) => {
const token = this.token || this.getToken();
if (token) {
opts.headers = {
...opts.headers,
Authorization: `Bearer ${token}`,
};
}
return opts;
};
this.qws = new QueryWs({ url: opts?.url });
}
getToken() {
return this.storage.getItem(this.tokenName);
}
saveToken(token: string) {
this.storage.setItem(this.tokenName, token);
}
removeToken() {
this.storage.removeItem(this.tokenName);
}
}
export { adapter }; export { adapter };

View File

@ -58,6 +58,7 @@ export class QueryWs {
}; };
ws.onclose = () => { ws.onclose = () => {
store.getState().setConnected(false); store.getState().setConnected(false);
store.getState().setStatus('disconnected');
this.ws = null; this.ws = null;
}; };
} }