20 Commits

Author SHA1 Message Date
dcab87c77a update: stop 2025-03-21 20:00:09 +08:00
a488c6ec48 feat: 添加response handle 2025-03-21 17:07:37 +08:00
17dbc08c69 fix types 2025-03-21 01:31:47 +08:00
49241a67f2 feat: change types 2025-03-21 01:29:24 +08:00
d0ce0b2c36 feat: 修改query,添加noMsg的确认 2025-03-20 12:33:36 +08:00
164c06c6a7 fix 2025-03-02 16:51:18 +08:00
64aa095ffe add query-ai 2025-03-02 12:14:09 +08:00
3a8396279b feat: 优化query,添加别名queryFetch 2025-03-02 09:11:59 +08:00
0b575d44c0 update pkgs 2025-03-01 23:14:24 +08:00
71448a2bdd fix: query add try catch 2025-03-01 17:41:35 +08:00
0fd19803f8 test: test demo 2024-12-25 20:14:50 +08:00
b4e4b55e1a fix: remove default new, becaule effect question 2024-11-30 00:13:59 +08:00
114350a2ca add npm rc for env 2024-11-18 02:16:12 +08:00
63cb0162df fix: exports browser default query module 2024-11-02 23:50:46 +08:00
61d949cc7c feat: 更新打包方式,dts 2024-11-02 22:12:36 +08:00
157fd4878a feat: 更新初始化client和timeout为3分钟 2024-10-16 19:16:34 +08:00
8c3025a6b3 docs: 修改介绍 2024-10-16 00:33:10 +08:00
77e6394266 add io and remove adapter
Some checks failed
Publish to npm / publish (push) Has been cancelled
2024-10-06 12:48:10 +08:00
4e38c3a74e Connect and return true 2024-10-01 00:57:17 +08:00
3f8971350e fix: export queryWs 2024-09-29 01:11:48 +08:00
23 changed files with 520 additions and 528 deletions

7
.gitignore vendored
View File

@@ -1,2 +1,9 @@
node_modules node_modules
dist dist
build
.cache
.DS_Store
*.log
.turbo

3
.npmrc Normal file
View File

@@ -0,0 +1,3 @@
//npm.xiongxiao.me/:_authToken=${ME_NPM_TOKEN}
@abearxiong:registry=https://npm.pkg.github.com
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

24
demo/backend/app.ts Normal file
View File

@@ -0,0 +1,24 @@
import { App } from '@kevisual/router';
const app = new App({
io: true,
});
app
.route({
path: 'test',
key: 'test',
})
.define(async (ctx) => {
ctx.body = 'test';
})
.addTo(app);
app.listen(4000, () => {
console.log('Server is running at http://localhost:4000');
});
app.io.addListener('subscribe', async ({ data, end, ws }) => {
console.log('A user connected', data);
ws.send('Hello World');
});

View File

@@ -8,6 +8,8 @@
<body> <body>
<!-- Your content goes here --> <!-- Your content goes here -->
<script type="module" src="src/index.ts"></script> <!-- <script type="module" src="src/index.ts"></script> -->
<!-- 测试io -->
<script type="module" src="src/test2.ts"></script>
</body> </body>
</html> </html>

View File

@@ -10,9 +10,10 @@
"license": "ISC", "license": "ISC",
"description": "", "description": "",
"dependencies": { "dependencies": {
"@abearxiong/query": "file:.." "@abearxiong/query": "file:..",
"@kevisual/router": "0.0.6-alpha-4"
}, },
"devDependencies": { "devDependencies": {
"vite": "^5.4.3" "vite": "^6.0.5"
} }
} }

26
demo/src/test2.ts Normal file
View File

@@ -0,0 +1,26 @@
import { QueryClient } from '@abearxiong/query';
const query = new QueryClient({ url: '/api/router', io: true });
query.qws.listenConnect(() => {
console.log('Connected');
// query.qws.send({
// type: 'subscribe',
// });
// query.qws.connect().then((res) => {
// console.log('Connected', res);
// query.qws.send({
// type: 'subscribe',
// });
// });
});
query.qws.connect().then((res) => {
console.log('Connected', res);
query.qws.send({
type: 'subscribe',
});
query.qws.ws.addEventListener('message', (event) => {
console.log('get', event.data);
});
});

View File

@@ -1,213 +0,0 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
import type { Config } from 'jest';
import { defaults } from 'jest-config';
const config: Config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
globals: {
window: {},
},
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/y3/bq7hhg1x02x_3xqrx11sql840000gn/T/jest_dx",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
// coverageProvider: "babel",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// moduleNameMapper: {
// '(.*)': ['<rootDir>/$1', '<rootDir>/$1', '<rootDir>/$1'],
// },
// moduleNameMapper: {
// '@/(.*)': ['<rootDir>/$1', '<rootDir>/$1', '<rootDir>/$1'],
// },
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// preset: 'ts-jest',
preset: 'ts-jest/presets/default-esm',
// transform: {
// '^.+\\.ts?$': 'babel-jest',
// },
transform: {
// '^.+\\.(ts|js)x?$': 'ts-jest',
'^.+\\.(ts|js)x?$': ['ts-jest', { useESM: true }],
},
// "testRegex": "/test/.*\\.(test|spec)\\.(ts)$",
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: 'node',
testEnvironment: 'node',
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: [
'/node_modules/',
'<rootDir>/node_modules/(?!(quill-mention)/)',
],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
module.exports = config;

View File

@@ -1,6 +1,6 @@
{ {
"name": "@kevisual/query", "name": "@kevisual/query",
"version": "0.0.6", "version": "0.0.13",
"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",
@@ -8,7 +8,7 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"build": "npm run clean && rollup -c", "build": "npm run clean && rollup -c",
"test": "NODE_ENV=development node --experimental-vm-modules node_modules/jest/bin/jest.js --detectOpenHandles", "build:app": "npm run build && rsync dist/* ../deploy/dist",
"clean": "rm -rf dist" "clean": "rm -rf dist"
}, },
"files": [ "files": [
@@ -22,15 +22,16 @@
"license": "ISC", "license": "ISC",
"description": "", "description": "",
"devDependencies": { "devDependencies": {
"@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-typescript": "^11.1.6", "@rollup/plugin-typescript": "^12.1.2",
"rollup": "^4.21.2", "rollup": "^4.36.0",
"rollup-plugin-dts": "^6.2.0",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"tslib": "^2.7.0", "tslib": "^2.8.1",
"zustand": "^4.5.5", "typescript": "^5.8.2",
"typescript": "^5.5.4" "zustand": "^5.0.3"
}, },
"packageManager": "yarn@1.22.19+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447", "packageManager": "yarn@1.22.22",
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
}, },
@@ -40,16 +41,23 @@
}, },
"exports": { "exports": {
".": { ".": {
"import": "./dist/index.js", "import": "./dist/query-browser.js",
"require": "./dist/index.js" "require": "./dist/query-browser.js"
}, },
"./node": { "./query": {
"import": "./dist/node-adapter.js", "import": "./dist/query.js",
"require": "./dist/node-adapter.js" "require": "./dist/query.js"
}, },
"./ws": { "./ws": {
"import": "./dist/ws.js", "import": "./dist/query-ws.js",
"require": "./dist/ws.js" "require": "./dist/query-ws.js"
},
"./query-ai": {
"import": "./dist/query-ai.js",
"require": "./dist/query-ai.js"
} }
},
"dependencies": {
"openai": "^4.88.0"
} }
} }

View File

@@ -4,6 +4,8 @@
主要目的:请求路径默认`/api/router`,使用`post`,`post`的数据分流使用`path``key`. 主要目的:请求路径默认`/api/router`,使用`post`,`post`的数据分流使用`path``key`.
适配后端的项目 [@kevisual/router](https://git.xiongxiao.me/kevisual/router)
## query ## query

View File

@@ -2,7 +2,7 @@
import typescript from '@rollup/plugin-typescript'; import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve'; import resolve from '@rollup/plugin-node-resolve';
import { dts } from 'rollup-plugin-dts';
/** /**
* @type {import('rollup').RollupOptions} * @type {import('rollup').RollupOptions}
*/ */
@@ -10,43 +10,91 @@ export default [
{ {
input: 'src/index.ts', // TypeScript 入口文件 input: 'src/index.ts', // TypeScript 入口文件
output: { output: {
file: 'dist/index.js', // 输出文件 file: 'dist/query-browser.js', // 输出文件
format: 'es', // 输出格式设置为 ES 模块 format: 'es', // 输出格式设置为 ES 模块
}, },
plugins: [ plugins: [
resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块 resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
typescript({ typescript(), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
allowImportingTsExtensions: true,
noEmit: true,
}), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
], ],
}, },
{ {
input: 'src/node-adapter.ts', // TypeScript 入口文件 input: 'src/index.ts', // TypeScript 入口文件
output: { output: {
file: 'dist/node-adapter.js', // 输出文件 file: 'dist/query-browser.d.ts', // 输出文件
format: 'es', // 输出格式设置为 ES 模块
},
plugins: [dts()],
},
{
input: 'src/query.ts',
output: {
file: 'dist/query.js',
format: 'es',
},
moduleSideEffects: false, // 确保无副作用的模块能被完全 tree-shake
propertyReadSideEffects: false,
plugins: [resolve(), typescript()],
},
{
input: 'src/query.ts',
output: {
file: 'dist/query.d.ts',
format: 'es',
},
plugins: [dts()],
},
{
input: 'src/ws.ts', // TypeScript 入口文件
output: {
file: 'dist/query-ws.js', // 输出文件
format: 'es', // 输出格式设置为 ES 模块 format: 'es', // 输出格式设置为 ES 模块
}, },
plugins: [ plugins: [
resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块 resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
typescript({ typescript(), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
allowImportingTsExtensions: true,
noEmit: true,
}), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
], ],
}, },
{ {
input: 'src/ws.ts', // TypeScript 入口文件 input: 'src/ws.ts', // TypeScript 入口文件
output: { output: {
file: 'dist/ws.js', // 输出文件 file: 'dist/query-ws.d.ts', // 输出文件
format: 'es', // 输出格式设置为 ES 模块 format: 'es', // 输出格式设置为 ES 模块
}, },
plugins: [ plugins: [dts()],
resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块 },
typescript({ {
allowImportingTsExtensions: true, input: 'src/adapter.ts',
noEmit: true, output: {
}), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件 file: 'dist/query-adapter.js',
], format: 'es',
},
plugins: [resolve(), typescript()],
},
{
input: 'src/adapter.ts', // TypeScript 入口文件
output: {
file: 'dist/query-adapter.d.ts', // 输出文件
format: 'es', // 输出格式设置为 ES 模块
},
plugins: [dts()],
},
{
input: 'src/query-ai.ts',
output: {
file: 'dist/query-ai.js',
format: 'es',
},
plugins: [resolve(), typescript()],
},
{
input: 'src/query-ai.ts', // TypeScript 入口文件
output: {
file: 'dist/query-ai.d.ts', // 输出文件
format: 'es', // 输出格式设置为 ES 模块
},
plugins: [dts()],
}, },
]; ];

View File

@@ -4,10 +4,17 @@ type AdapterOpts = {
body?: Record<string, any>; body?: Record<string, any>;
timeout?: number; timeout?: number;
}; };
export const adapter = async (opts: AdapterOpts) => {
/**
*
* @param opts
* @param overloadOpts 覆盖fetch的默认配置
* @returns
*/
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 timeout = opts.timeout || 60000; // 默认超时时间为 60s const timeout = opts.timeout || 60000 * 3; // 默认超时时间为 60s * 3
const timer = setTimeout(() => { const timer = setTimeout(() => {
controller.abort(); controller.abort();
}, timeout); }, timeout);
@@ -20,6 +27,7 @@ export const adapter = async (opts: AdapterOpts) => {
}, },
body: JSON.stringify(opts.body), body: JSON.stringify(opts.body),
signal, signal,
...overloadOpts,
}) })
.then((response) => { .then((response) => {
// 获取 Content-Type 头部信息 // 获取 Content-Type 头部信息
@@ -44,3 +52,7 @@ export const adapter = async (opts: AdapterOpts) => {
clearTimeout(timer); clearTimeout(timer);
}); });
}; };
/**
* adapter
*/
export const queryFetch = adapter;

View File

@@ -1,128 +1 @@
import { adapter } from './adapter.ts'; export * from './query-browser.ts'
import { QueryWs } from './ws.ts';
export { QueryOpts };
type Fn = (opts: {
url?: string;
headers?: Record<string, string>;
body?: Record<string, any>;
[key: string]: any;
timeout?: number;
}) => Promise<Record<string, any>>;
type QueryOpts = {
url?: string;
adapter?: typeof adapter;
headers?: Record<string, string>;
timeout?: number;
};
type Data = {
path?: string;
key?: string;
payload?: Record<string, any>;
[key: string]: any;
};
type Result<S = any> = {
code: number;
data?: S;
message?: string;
success: boolean;
};
// 额外功能
type DataOpts = Partial<QueryOpts> & {
beforeRequest?: Fn;
afterResponse?: (result: Result) => Promise<any>;
};
/**
* const query = new Query();
* const res = await query.post({
* path: 'demo',
* key: '1',
* });
*
* U是参数 V是返回值
*/
export class Query<U = any, V = any> {
adapter: typeof adapter;
url: string;
beforeRequest?: Fn;
afterResponse?: (result: Result) => Promise<any>;
headers?: Record<string, string>;
timeout?: number;
constructor(opts?: QueryOpts) {
this.adapter = opts?.adapter || adapter;
this.url = opts?.url || '/api/router';
this.headers = opts?.headers || {
'Content-Type': 'application/json',
};
this.timeout = opts?.timeout || 60000; // 默认超时时间为 60s
}
async get<T = any, S = any>(params: Record<string, any> & Data & U & T, options?: DataOpts): Promise<Result<V & S>> {
return this.post(params, options);
}
async post<T = any, S = any>(body: Record<string, any> & Data & T, options?: DataOpts): Promise<Result<S>> {
const url = options?.url || this.url;
const headers = { ...this.headers, ...options?.headers };
const adapter = options?.adapter || this.adapter;
const beforeRequest = options?.beforeRequest || this.beforeRequest;
const afterResponse = options?.afterResponse || this.afterResponse;
const timeout = options?.timeout || this.timeout;
const req = {
url: url,
headers: headers,
body,
timeout,
};
if (beforeRequest) {
await beforeRequest(req);
}
return adapter(req).then(async (res) => {
res.success = res.code === 200;
if (afterResponse) {
return await afterResponse(res);
}
return res;
});
}
before(fn: Fn) {
this.beforeRequest = fn;
}
after(fn: (result: Result) => Promise<any>) {
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 };

View File

@@ -1,57 +0,0 @@
import http from 'http';
type AdapterOpts = {
url: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
export const nodeAdapter = async (opts: AdapterOpts): Promise<any> => {
return new Promise((resolve, reject) => {
const postData = JSON.stringify(opts.body || '');
const _url = new URL(opts.url);
const { hostname, port, pathname } = _url;
const options = {
hostname: hostname,
port: port,
path: pathname || '/api/router',
method: 'POST', // Assuming it's a POST request
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
...opts.headers,
},
};
const req = http.request(options, (res) => {
let data = '';
// Collect data chunks
res.on('data', (chunk) => {
data += chunk;
});
// Resolve when the response is complete
res.on('end', () => {
try {
const parsedData = JSON.parse(data);
resolve(parsedData);
} catch (error) {
reject(error);
}
});
});
// Handle request errors
req.on('error', (error) => {
reject(error);
});
// Write the request body and end the request
if (opts.body) {
req.write(postData);
}
req.end();
});
};
export const adapter = nodeAdapter;

58
src/query-ai.ts Normal file
View File

@@ -0,0 +1,58 @@
import OpenAI, { ClientOptions } from 'openai';
import type { RequestOptions } from 'openai/core.mjs';
type QueryOpts = {
/**
* OpenAI model name, example: deepseek-chat
*/
model: string;
/**
* OpenAI client options
* QueryAi.init() will be called with these options
*/
openAiOpts?: ClientOptions;
openai?: OpenAI;
};
export class QueryAI {
private openai: OpenAI;
model?: string;
constructor(opts?: QueryOpts) {
this.model = opts?.model;
if (opts?.openai) {
this.openai = opts.openai;
} else if (opts?.openAiOpts) {
this.init(opts?.openAiOpts);
}
}
init(opts: ClientOptions) {
this.openai = new OpenAI(opts);
}
async query(prompt: string, opts?: RequestOptions) {
return this.openai.chat.completions.create({
model: this.model,
messages: [
{
role: 'system',
content: prompt,
},
],
stream: false,
...opts,
});
}
async queryAsync(prompt: string, opts?: RequestOptions) {
return this.openai.chat.completions.create({
model: this.model,
messages: [
{
role: 'system',
content: prompt,
},
],
stream: true,
...opts,
});
}
}
export { OpenAI };

55
src/query-browser.ts Normal file
View File

@@ -0,0 +1,55 @@
import { adapter } from './adapter.ts';
import { QueryWs, QueryWsOpts } from './ws.ts';
import { Query } from './query.ts';
export { QueryOpts, QueryWs, Query, QueryWsOpts, adapter };
type QueryOpts = {
url?: string;
adapter?: typeof adapter;
headers?: Record<string, string>;
timeout?: number;
};
/**
* 前端调用后端QueryRouter
*/
export class QueryClient extends Query {
tokenName: string;
storage: Storage;
token: string;
// 默认不使用ws
qws: QueryWs;
constructor(opts?: QueryOpts & { tokenName?: string; storage?: Storage; io?: boolean }) {
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;
};
if (opts?.io) {
this.createWs();
}
}
createWs(opts?: QueryWsOpts) {
this.qws = new QueryWs({ url: this.url, ...opts });
}
getToken() {
return this.storage.getItem(this.tokenName);
}
saveToken(token: string) {
this.storage.setItem(this.tokenName, token);
}
removeToken() {
this.storage.removeItem(this.tokenName);
}
}
// 移除默认生成的实例
// export const client = new QueryClient();

202
src/query.ts Normal file
View File

@@ -0,0 +1,202 @@
import { adapter } from './adapter.ts';
/**
* 请求前处理函数
* @param opts 请求配置
* @returns 请求配置
*/
export type Fn = (opts: {
url?: string;
headers?: Record<string, string>;
body?: Record<string, any>;
[key: string]: any;
timeout?: number;
}) => Promise<Record<string, any>>;
export type QueryOpts = {
url?: string;
adapter?: typeof adapter;
headers?: Record<string, string>;
timeout?: number;
};
export type Data = {
path?: string;
key?: string;
payload?: Record<string, any>;
[key: string]: any;
};
export type Result<S = any> = {
code: number;
data?: S;
message?: string;
success: boolean;
/**
* 是否不返回 message
*/
noMsg?: boolean;
/**
* 显示错误, 当 handle的信息被处理的时候如果不是success同时自己设置了noMsg那么就不显示错误信息了因为被处理。
*
* 日常: fetch().then(res=>if(res.sucess){message.error('error')})的时候比如401被处理过了就不再提示401错误了。
*
*/
showError: (fn?: () => void) => void;
};
// 额外功能
export type DataOpts = Partial<QueryOpts> & {
beforeRequest?: Fn;
afterResponse?: <S = any>(result: Result<S>, ctx?: { req?: any; res?: any; fetch?: any }) => Promise<S>;
};
/**
* 设置基础响应, 设置 success 和 showError,
* success 是 code 是否等于 200
* showError 是 如果 success 为 false 且 noMsg 为 false, 则调用 showError
* @param res 响应
*/
export const setBaseResponse = (res: Result) => {
res.success = res.code === 200;
/**
* 显示错误
* @param fn 错误处理函数
*/
res.showError = (fn?: () => void) => {
if (!res.success && !res.noMsg) {
fn?.();
}
};
};
/**
* const query = new Query();
* const res = await query.post({
* path: 'demo',
* key: '1',
* });
*
* U是参数 V是返回值
*/
export class Query {
adapter: typeof adapter;
url: string;
beforeRequest?: Fn;
afterResponse?: DataOpts['afterResponse'];
headers?: Record<string, string>;
timeout?: number;
/**
* 需要突然停止请求比如401的时候
*/
stop?: boolean;
constructor(opts?: QueryOpts) {
this.adapter = opts?.adapter || adapter;
this.url = opts?.url || '/api/router';
this.headers = opts?.headers || {
'Content-Type': 'application/json',
};
this.timeout = opts?.timeout || 60000 * 3; // 默认超时时间为 60s * 3
}
/**
* 突然停止请求
*/
setStop(stop: boolean) {
this.stop = stop;
}
/**
* 发送 get 请求,转到 post 请求
* T是请求类型自定义
* S是返回类型自定义
* @param params 请求参数
* @param options 请求配置
* @returns 请求结果
*/
async get<R = any, P = any>(params: Data & P, options?: DataOpts): Promise<Result<R>> {
return this.post(params, options);
}
/**
* 发送 post 请求
* T是请求类型自定义
* S是返回类型自定义
* @param body 请求体
* @param options 请求配置
* @returns 请求结果
*/
async post<R = any, P = any>(body: Data & P, options?: DataOpts): Promise<Result<R>> {
const url = options?.url || this.url;
const headers = { ...this.headers, ...options?.headers };
const adapter = options?.adapter || this.adapter;
const beforeRequest = options?.beforeRequest || this.beforeRequest;
const afterResponse = options?.afterResponse || this.afterResponse;
const timeout = options?.timeout || this.timeout;
const req = {
url: url,
headers: headers,
body,
timeout,
};
try {
if (beforeRequest) {
await beforeRequest(req);
}
} catch (e) {
console.error('request beforeFn error', e, req);
return {
code: 500,
success: false,
message: 'api request beforeFn error',
showError: () => {},
};
}
if (this.stop) {
const that = this;
await new Promise((resolve) => {
let timer = 0;
const detect = setInterval(() => {
if (!that.stop) {
clearInterval(detect);
resolve(true);
}
timer++;
if (timer > 30) {
console.error('request stop: timeout', req.url, timer);
}
}, 1000);
});
}
return adapter(req).then(async (res) => {
try {
setBaseResponse(res);
if (afterResponse) {
return await afterResponse(res, {
req,
res,
fetch: adapter,
});
}
return res;
} catch (e) {
console.error('request error', e, req);
return {
code: 500,
success: false,
message: 'api request afterFn error',
showError: () => {},
};
}
});
}
/**
* 请求前处理,设置请求前处理函数
* @param fn 处理函数
*/
before(fn: Fn) {
this.beforeRequest = fn;
}
/**
* 请求后处理,设置请求后处理函数
* @param fn 处理函数
*/
after(fn: (result: Result, req?: any) => Promise<any>) {
this.afterResponse = fn;
}
}
export { adapter };

View File

@@ -9,7 +9,7 @@ type QueryWsStore = {
}; };
export type QuerySelectState = 'connecting' | 'connected' | 'disconnected'; export type QuerySelectState = 'connecting' | 'connected' | 'disconnected';
export type QueryWsStoreListener = (newState: QueryWsStore, oldState: QueryWsStore) => void; export type QueryWsStoreListener = (newState: QueryWsStore, oldState: QueryWsStore) => void;
type QueryWsOpts = { export type QueryWsOpts = {
url?: string; url?: string;
store?: StoreApi<QueryWsStore>; store?: StoreApi<QueryWsStore>;
ws?: WebSocket; ws?: WebSocket;
@@ -45,22 +45,31 @@ export class QueryWs {
/** /**
* 连接 WebSocket * 连接 WebSocket
*/ */
connect() { async connect(opts?: { timeout?: number }) {
const store = this.store; const store = this.store;
const connected = store.getState().connected; const connected = store.getState().connected;
if (connected) { if (connected) {
return; return Promise.resolve(true);
} }
const ws = this.ws || new WebSocket(this.url); return new Promise((resolve, reject) => {
ws.onopen = () => { const ws = this.ws || new WebSocket(this.url);
store.getState().setConnected(true); const timeout = opts?.timeout || 5 * 60 * 1000; // 默认 2 分钟
store.getState().setStatus('connected'); let timer = setTimeout(() => {
}; console.error('WebSocket 连接超时');
ws.onclose = () => { reject('timeout');
store.getState().setConnected(false); }, timeout);
store.getState().setStatus('disconnected'); ws.onopen = () => {
this.ws = null; store.getState().setConnected(true);
}; store.getState().setStatus('connected');
resolve(true);
clearTimeout(timer);
};
ws.onclose = () => {
store.getState().setConnected(false);
store.getState().setStatus('disconnected');
this.ws = null;
};
});
} }
listenConnect(callback: () => void) { listenConnect(callback: () => void) {
@@ -141,4 +150,10 @@ export class QueryWs {
ws.send(data as string); ws.send(data as string);
} }
} }
getOpen() {
if (!this.ws) {
return false;
}
return this.ws.readyState === WebSocket.OPEN;
}
} }

View File

@@ -1,12 +0,0 @@
import { adapter } from '../src/adapter';
const hostname = 'localhost:3002';
describe('Adapter', () => {
// 编写一个测试用例
// yarn test --testNamePattern='Adapter'
test('Adapter:First', () => {
adapter({ url: hostname + '/api/router' }).then((res) => {
expect(res).toEqual({ id: 1 });
});
});
});

View File

@@ -1,7 +0,0 @@
describe('Hello', () => {
// 编写一个测试用例
// yarn test --testNamePattern='Hello'
test('Hello World', () => {
console.log('Hello World');
});
});

View File

@@ -1,17 +0,0 @@
import { nodeAdapter } from "../src/node-adapter";
// tsx test/node-adapter.ts
const main = async () => {
const res = await nodeAdapter({
url: 'http://127.0.0.1/api/router',
headers: {
'Content-Type': 'application/json',
},
body: {
path: 'demo',
key: '1',
},
});
console.log(res);
};
main();

View File

@@ -1,25 +0,0 @@
import { Query } from './../src/index';
const query = new Query({ url: '/api/router' });
describe('Query', () => {
// 编写一个测试用例
// yarn test --testNamePattern='Query'
test('Query:First', async () => {
console.log('Query');
});
});
// test('query', async () => {
// query.get({ id: 1 }).then((res) => {
// expect(res).toEqual({ id: 1 });
// });
// }
// describe('Hello', () => {
// // 编写一个测试用例
// // yarn test --testNamePattern='Hello'
// test('Hello World', () => {
// console.log('Hello World');
// });
// });

View File

@@ -1,13 +0,0 @@
import { QueryWs } from '../src/ws';
const queryWs = new QueryWs({ url: '/api/ws' });
queryWs.listenConnect(() => {
console.log('Connected');
});
queryWs.store.getState().setConnected(true);
queryWs.store.getState().setConnected(false);
setTimeout(() => {
queryWs.store.getState().setConnected(true);
}, 1000);

View File

@@ -8,10 +8,10 @@
"allowJs": true, "allowJs": true,
"newLine": "LF", "newLine": "LF",
"baseUrl": "./", "baseUrl": "./",
"declaration": false,
"typeRoots": [ "typeRoots": [
"node_modules/@types", "node_modules/@types",
], ],
"declaration": true,
"noEmit": true, "noEmit": true,
"allowImportingTsExtensions": true, "allowImportingTsExtensions": true,
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",