Compare commits

..

33 Commits

Author SHA1 Message Date
b53968df8b update no Stop 2025-06-18 14:59:56 +08:00
ca154ba883 feat: update new options 2025-06-07 19:07:28 +08:00
14dec5f5c5 add query adapter 2025-06-07 17:00:30 +08:00
452f821d06 fix: fix adapter 2025-06-03 21:12:33 +08:00
27adb05c39 fix: fix bugs 2025-06-03 20:04:37 +08:00
66905f13a9 "chore: 更新依赖及适配Blob响应" 2025-06-02 11:36:59 +08:00
366840bb1d fix: change base query 2025-05-25 00:06:10 +08:00
8385ab05f6 fix 2025-05-24 09:26:10 +08:00
515c6e6cf7 query add chain 2025-05-20 10:14:15 +08:00
1104efaa1a perf 2025-05-15 22:21:52 +08:00
cf6ca31aa4 query add cacel request 2025-04-06 21:35:29 +08:00
320bc93c69 temp 2025-04-05 22:27:46 +08:00
0570acb78f temp 2025-03-30 00:36:51 +08:00
fd5437292a fix: fix onopen 2025-03-22 14:34:17 +08:00
64b37e369d types change for afterResponse 2025-03-22 13:29:02 +08:00
8f85ed4d4d feat: 支持GET请求 因为GET的请求可以缓存 2025-03-22 13:19:40 +08:00
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
23 changed files with 729 additions and 552 deletions

9
.gitignore vendored
View File

@ -1,2 +1,9 @@
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>
<!-- 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>
</html>

View File

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

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

@ -0,0 +1,27 @@
// @ts-ignore
import { QueryClient } from '@kevisual/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",
"version": "0.0.7-alpha.1",
"version": "0.0.29",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
@ -8,7 +8,8 @@
"type": "module",
"scripts": {
"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",
"dev:lib": "rollup -c -w",
"clean": "rm -rf dist"
},
"files": [
@ -22,15 +23,16 @@
"license": "ISC",
"description": "",
"devDependencies": {
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-typescript": "^11.1.6",
"rollup": "^4.21.2",
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-typescript": "^12.1.2",
"rollup": "^4.41.1",
"rollup-plugin-dts": "^6.2.1",
"ts-node": "^10.9.2",
"tslib": "^2.7.0",
"zustand": "^4.5.5",
"typescript": "^5.5.4"
"tslib": "^2.8.1",
"typescript": "^5.8.3",
"zustand": "^5.0.5"
},
"packageManager": "yarn@1.22.19+sha1.4ba7fc5c6e704fce2066ecbfb0b0d8976fe62447",
"packageManager": "yarn@1.22.22",
"publishConfig": {
"access": "public"
},
@ -40,16 +42,23 @@
},
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.js"
"import": "./dist/query-browser.js",
"require": "./dist/query-browser.js"
},
"./node": {
"import": "./dist/node-adapter.js",
"require": "./dist/node-adapter.js"
"./query": {
"import": "./dist/query.js",
"require": "./dist/query.js"
},
"./ws": {
"import": "./dist/ws.js",
"require": "./dist/ws.js"
"import": "./dist/query-ws.js",
"require": "./dist/query-ws.js"
},
"./query-ai": {
"import": "./dist/query-ai.js",
"require": "./dist/query-ai.js"
}
},
"dependencies": {
"openai": "^5.0.1"
}
}

View File

@ -1,11 +1,12 @@
# query
应的 fetch 内容的一部分功能的封装
fetch 功能的的一部分功能的封装。主要处理header的token的提交和response中的处理json
主要目的:请求路径默认`/api/router`,使用`post`,`post`的数据分流使用`path``key`.
## query
适配后端的项目 [@kevisual/router](https://git.xiongxiao.me/kevisual/router)
## query
```ts
const query = new Query();
@ -33,4 +34,21 @@ type Data = {
type DataOpts = Partial<QueryOpts> & {
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);
```

View File

@ -2,7 +2,7 @@
import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import { dts } from 'rollup-plugin-dts';
/**
* @type {import('rollup').RollupOptions}
*/
@ -10,45 +10,91 @@ export default [
{
input: 'src/index.ts', // TypeScript 入口文件
output: {
file: 'dist/index.js', // 输出文件
file: 'dist/query-browser.js', // 输出文件
format: 'es', // 输出格式设置为 ES 模块
},
plugins: [
resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
typescript({
allowImportingTsExtensions: true,
noEmit: true,
exclude: ['src/node-adapter.ts'],
}), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
typescript(), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
],
},
// {
// input: 'src/node-adapter.ts', // TypeScript 入口文件
// output: {
// file: 'dist/node-adapter.js', // 输出文件
// format: 'es', // 输出格式设置为 ES 模块
// },
// plugins: [
// resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
// typescript({
// allowImportingTsExtensions: true,
// noEmit: true,
// }), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
// ],
// },
{
input: 'src/index.ts', // TypeScript 入口文件
output: {
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/ws.js', // 输出文件
file: 'dist/query-ws.js', // 输出文件
format: 'es', // 输出格式设置为 ES 模块
},
plugins: [
resolve(), // 使用 @rollup/plugin-node-resolve 解析 node_modules 中的模块
typescript({
allowImportingTsExtensions: true,
noEmit: true,
declaration: false,
}), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
typescript(), // 使用 @rollup/plugin-typescript 处理 TypeScript 文件
],
},
{
input: 'src/ws.ts', // TypeScript 入口文件
output: {
file: 'dist/query-ws.d.ts', // 输出文件
format: 'es', // 输出格式设置为 ES 模块
},
plugins: [dts()],
},
{
input: 'src/adapter.ts',
output: {
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

@ -1,34 +1,89 @@
type AdapterOpts = {
url: string;
export const methods = ['GET', 'POST'] as const;
export type Method = (typeof methods)[number];
type SimpleObject = Record<string, any>;
export type AdapterOpts = {
url?: string;
headers?: Record<string, string>;
body?: Record<string, any>;
body?: Record<string, any> | FormData; // body 可以是对象、字符串或 FormData
timeout?: number;
method?: Method;
isBlob?: boolean; // 是否返回 Blob 对象, 第一优先
isText?: boolean; // 是否返回文本内容, 第二优先
isPostFile?: boolean; // 是否为文件上传
};
export const adapter = async (opts: AdapterOpts) => {
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 overloadOpts fetch的默认配置
* @returns
*/
export const adapter = async (opts: AdapterOpts = {}, overloadOpts?: RequestInit) => {
const controller = new AbortController();
const signal = controller.signal;
const timeout = opts.timeout || 60000; // 默认超时时间为 60s
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 timer = setTimeout(() => {
controller.abort();
}, timeout);
return fetch(opts.url, {
method: 'POST',
headers: {
let method = overloadOpts?.method || opts?.method || 'POST';
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';
if (isGet) {
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',
...opts.headers,
},
body: JSON.stringify(opts.body),
...headers,
};
body = JSON.stringify(opts.body); // 否则将对象转换为 JSON 字符串
}
return fetch(url, {
method: method.toUpperCase(),
signal,
body: body,
...overloadOpts,
headers: headers,
})
.then((response) => {
.then(async (response) => {
// 获取 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')) {
return response.json(); // 解析为 JSON
if (isJson && !isText) {
return await response.json(); // 解析为 JSON
} else if (isTextForContentType(contentType)) {
return {
code: 200,
status: response.status,
data: await response.text(), // 直接返回文本内容
};
} else {
return response.text(); // 解析为文本
return response;
}
})
.catch((err) => {
@ -44,3 +99,7 @@ export const adapter = async (opts: AdapterOpts) => {
clearTimeout(timer);
});
};
/**
* adapter
*/
export const queryFetch = adapter;

View File

@ -1,133 +1 @@
import { adapter } from './adapter.ts';
import { QueryWs, QueryWsOpts } from './ws.ts';
export { QueryOpts, QueryWs };
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; 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 });
}
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 * from './query-browser.ts'

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 };

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

@ -0,0 +1,56 @@
import { adapter } from './adapter.ts';
import { QueryWs, QueryWsOpts } from './ws.ts';
import { Query, ClientQuery } from './query.ts';
import { BaseQuery, wrapperError } from './query.ts';
export { QueryOpts, QueryWs, ClientQuery, Query, QueryWsOpts, adapter, BaseQuery, wrapperError };
export type { DataOpts, Result, Data } from './query.ts';
type QueryOpts = {
url?: string;
adapter?: typeof adapter;
headers?: Record<string, string>;
timeout?: number;
};
/**
* QueryRouter, beforeRequest wss
*/
export class QueryClient extends Query {
tokenName: string;
storage: Storage;
token: string;
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();

282
src/query.ts Normal file
View File

@ -0,0 +1,282 @@
import { adapter, isTextForContentType, Method, AdapterOpts } from './adapter.ts';
import type { QueryWs } from './ws.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> | false>;
export type QueryOpts = {
adapter?: typeof adapter;
[key: string]: any;
} & AdapterOpts;
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的信息被处理的时候successnoMsg
*
* 日常: fetch().then(res=>if(res.sucess){message.error('error')})401401
*
*/
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<Result<S>>;
/**
* stop的时候不请求
*/
noStop?: boolean;
};
/**
* , success showError,
* success code 200
* showError success false noMsg false, showError
* @param res
*/
export const setBaseResponse = (res: Partial<Result>) => {
res.success = res.code === 200;
/**
*
* @param fn
*/
res.showError = (fn?: () => void) => {
if (!res.success && !res.noMsg) {
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 res = await query.post({
* path: 'demo',
* key: '1',
* });
*
* U是参数 V是返回值
*/
export class Query {
adapter: typeof adapter;
url: string;
beforeRequest?: DataOpts['beforeRequest'];
afterResponse?: DataOpts['afterResponse'];
headers?: Record<string, string>;
timeout?: number;
/**
* 401
*/
stop?: boolean;
// 默认不使用ws
qws: QueryWs;
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
}
setQueryWs(qws: QueryWs) {
this.qws = qws;
}
/**
*
*/
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, adapter, beforeRequest, afterResponse, timeout, ...rest } = options || {};
const _headers = { ...this.headers, ...headers };
const _adapter = adapter || this.adapter;
const _beforeRequest = beforeRequest || this.beforeRequest;
const _afterResponse = afterResponse || this.afterResponse;
const _timeout = timeout || this.timeout;
const req = {
url: url,
headers: _headers,
body,
timeout: _timeout,
...rest,
};
try {
if (_beforeRequest) {
const res = await _beforeRequest(req);
if (res === false) {
return wrapperError({
code: 500,
message: 'request is cancel',
// @ts-ignore
req: req,
});
}
}
} catch (e) {
console.error('request beforeFn error', e, req);
return wrapperError({
code: 500,
message: 'api request beforeFn error',
// @ts-ignore
req: req,
});
}
if (this.stop && !options?.noStop) {
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 afterFn error', e, req);
return wrapperError({
code: 500,
message: 'api request afterFn error',
// @ts-ignore
req: req,
});
}
});
}
/**
*
* @param fn
*/
before(fn: DataOpts['beforeRequest']) {
this.beforeRequest = fn;
}
/**
*
* @param fn
*/
after(fn: DataOpts['afterResponse']) {
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 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' });
}
}

View File

@ -47,31 +47,42 @@ export class QueryWs {
*/
async connect(opts?: { timeout?: number }) {
const store = this.store;
const that = this;
const connected = store.getState().connected;
if (connected) {
return Promise.resolve(true);
}
return new Promise((resolve, reject) => {
const ws = this.ws || new WebSocket(this.url);
const timeout = opts?.timeout || 5 * 60 * 1000; // 默认 2 分钟
const ws = that.ws || new WebSocket(that.url);
const timeout = opts?.timeout || 5 * 60 * 1000; // 默认 5 分钟
let timer = setTimeout(() => {
console.error('WebSocket 连接超时');
reject('timeout');
const isOpen = ws.readyState === WebSocket.OPEN;
if (isOpen) {
console.log('WebSocket 连接成功 in timer');
resolve(true);
return;
}
console.error('WebSocket 连接超时', that.url);
resolve(false);
}, timeout);
ws.onopen = () => {
ws.onopen = (ev) => {
store.getState().setConnected(true);
store.getState().setStatus('connected');
resolve(true);
clearTimeout(timer);
};
ws.onclose = () => {
ws.onclose = (ev) => {
store.getState().setConnected(false);
store.getState().setStatus('disconnected');
this.ws = null;
};
});
}
/**
* ws.onopen
* @param callback
* @returns
*/
listenConnect(callback: () => void) {
const store = this.store;
const { connected } = store.getState();
@ -96,10 +107,41 @@ export class QueryWs {
);
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>(
fn: (data: U, event: MessageEvent) => void,
opts?: {
/**
* JSON
*/
isJson?: boolean;
/**
*
*/
selector?: (data: T) => U;
},
) {
@ -136,7 +178,26 @@ export class QueryWs {
store.getState().setConnected(false);
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 isJson = opts?.isJson ?? true;
const wrapper = opts?.wrapper;

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,
"newLine": "LF",
"baseUrl": "./",
"declaration": false,
"typeRoots": [
"node_modules/@types",
],
"declaration": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"moduleResolution": "NodeNext",