@bubblesjs/request 0.0.2 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +37 -36
  2. package/dist/index.js +152 -62
  3. package/package.json +13 -10
package/dist/index.d.ts CHANGED
@@ -1,51 +1,52 @@
1
- import * as alova0 from "alova";
2
- import { AlovaGenerics, AlovaOptions } from "alova";
1
+ import { AlovaGlobalCacheAdapter, AlovaRequestAdapter, GlobalCacheConfig, StatesExport, StatesHook } from "alova";
2
+ import { FetchRequestInit } from "alova/fetch";
3
3
 
4
4
  //#region src/index.d.ts
5
- interface statusMap {
6
- success?: number;
7
- unAuthorized?: number;
5
+ type MaybePromise<T> = T | Promise<T>;
6
+ type HeaderValue = string | number | boolean | null | undefined | (() => MaybePromise<string | number | boolean | null | undefined>);
7
+ type StatusMatcher<RE> = number | number[] | ((status: number, response: RE) => boolean);
8
+ type CodeMatcher = Array<number | string>;
9
+ interface StatusMap<RE = unknown> {
10
+ success?: StatusMatcher<RE>;
11
+ unAuthorized?: StatusMatcher<RE>;
8
12
  }
9
- interface codeMap {
10
- success?: number[];
11
- unAuthorized?: number[];
13
+ interface CodeMap {
14
+ success?: CodeMatcher;
15
+ unAuthorized?: CodeMatcher;
12
16
  }
13
- interface baseRequestOption<AG extends AlovaGenerics> {
17
+ interface RequestMeta {
18
+ isWrapped?: boolean;
19
+ isTransformResponse?: boolean;
20
+ isShowSuccessMessage?: boolean;
21
+ isShowErrorMessage?: boolean;
22
+ }
23
+ interface BaseRequestOption<RC extends object = FetchRequestInit, RE = Response, RH = Headers, SE extends StatesExport<any> = StatesExport<any>> extends RequestMeta {
14
24
  baseUrl?: string;
15
25
  timeout?: number;
16
- commonHeaders?: Record<string, string | (() => string)>;
17
- statusMap?: statusMap;
18
- codeMap?: codeMap;
26
+ commonHeaders?: Record<string, HeaderValue>;
27
+ statusMap?: StatusMap<RE>;
28
+ codeMap?: CodeMap;
29
+ responseCodeKey?: string;
19
30
  responseDataKey?: string;
20
31
  responseMessageKey?: string;
21
- isTransformResponse?: boolean;
22
- isShowSuccessMessage?: boolean;
32
+ cacheFor?: GlobalCacheConfig<any> | null;
33
+ cacheLogger?: boolean;
34
+ statesHook?: StatesHook<SE>;
23
35
  successDefaultMessage?: string;
24
- isShowErrorMessage?: boolean;
25
36
  errorDefaultMessage?: string;
26
- statesHook?: AlovaOptions<AG>['statesHook'];
27
37
  successMessageFunc?: (message: string) => void;
28
38
  errorMessageFunc?: (message: string) => void;
29
39
  unAuthorizedResponseFunc?: () => void;
30
- requestAdapter?: AlovaOptions<AG>['requestAdapter'];
31
- }
32
- interface CustomConfig {
33
- isTransformResponse?: boolean;
34
- isShowSuccessMessage?: boolean;
35
- isShowErrorMessage?: boolean;
40
+ requestAdapter?: AlovaRequestAdapter<RC, RE, RH>;
41
+ l1Cache?: AlovaGlobalCacheAdapter;
42
+ l2Cache?: AlovaGlobalCacheAdapter;
43
+ storageAdapter?: AlovaGlobalCacheAdapter;
36
44
  }
37
- type requestOption = baseRequestOption<AlovaGenerics> & CustomConfig;
38
- declare const createInstance: (option: requestOption) => alova0.Alova<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>>;
39
- declare const createDualCallInstance: (baseConfig: baseRequestOption<AlovaGenerics>) => {
40
- (option?: CustomConfig): alova0.Alova<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>>;
41
- Get: <Responded = unknown, Transformed = unknown>(url: string, config?: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
42
- Post: <Responded = unknown, Transformed = unknown>(url: string, data?: alova0.RequestBody, config?: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
43
- Put: <Responded = unknown, Transformed = unknown>(url: string, data?: alova0.RequestBody, config?: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
44
- Delete: <Responded = unknown, Transformed = unknown>(url: string, data?: alova0.RequestBody, config?: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
45
- Patch: <Responded = unknown, Transformed = unknown>(url: string, data?: alova0.RequestBody, config?: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
46
- Head: <Responded = unknown, Transformed = unknown>(url: string, config?: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
47
- Options: <Responded = unknown, Transformed = unknown>(url: string, config?: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
48
- Request: <Responded = unknown, Transformed = unknown>(config: any) => alova0.Method<alova0.RespondedAlovaGenerics<AlovaGenerics<any, any, any, any, any, alova0.AlovaDefaultCacheAdapter, alova0.AlovaDefaultCacheAdapter, any>, Responded, Transformed>>;
49
- };
45
+ type baseRequestOption<RC extends object = FetchRequestInit, RE = Response, RH = Headers, SE extends StatesExport<any> = StatesExport<any>> = BaseRequestOption<RC, RE, RH, SE>;
46
+ type RequestOption<RC extends object = FetchRequestInit, RE = Response, RH = Headers, SE extends StatesExport<any> = StatesExport<any>> = BaseRequestOption<RC, RE, RH, SE>;
47
+ declare function createInstance<RC extends object = FetchRequestInit, RE = Response, RH = Headers, SE extends StatesExport<any> = StatesExport<any>>(option?: RequestOption<RC, RE, RH, SE>): import("alova").Alova<import("alova").AlovaGenerics<any, any, RC, RE, RH, AlovaGlobalCacheAdapter, AlovaGlobalCacheAdapter, SE>>;
48
+ type RequestInstance<RC extends object = FetchRequestInit, RE = Response, RH = Headers, SE extends StatesExport<any> = StatesExport<any>> = ReturnType<typeof createInstance<RC, RE, RH, SE>>;
49
+ type DualCallInstance<RC extends object = FetchRequestInit, RE = Response, RH = Headers, SE extends StatesExport<any> = StatesExport<any>> = RequestInstance<RC, RE, RH, SE> & ((option?: RequestOption<RC, RE, RH, SE>) => RequestInstance<RC, RE, RH, SE>);
50
+ declare function createDualCallInstance<RC extends object = FetchRequestInit, RE = Response, RH = Headers, SE extends StatesExport<any> = StatesExport<any>>(baseConfig: BaseRequestOption<RC, RE, RH, SE>): DualCallInstance<RC, RE, RH, SE>;
50
51
  //#endregion
51
- export { CustomConfig, baseRequestOption, createDualCallInstance, createInstance };
52
+ export { BaseRequestOption, CodeMap, DualCallInstance, RequestInstance, RequestMeta, RequestOption, StatusMap, baseRequestOption, createDualCallInstance, createInstance };
package/dist/index.js CHANGED
@@ -1,79 +1,170 @@
1
+ import { deepMergeObject, isPlainObject, isReadableStream, tryParseJsonString } from "@bubblesjs/utils";
1
2
  import { createAlova } from "alova";
2
- import { deepMergeObject, isReadableStream } from "@bubblesjs/utils";
3
3
  import adapterFetch from "alova/fetch";
4
-
5
4
  //#region src/index.ts
6
- const createInstance = (option) => {
7
- const defaultOption = {
8
- baseUrl: "/",
9
- timeout: 0,
10
- statusMap: {
11
- success: 200,
12
- unAuthorized: 401
13
- },
14
- codeMap: {
15
- success: [200],
16
- unAuthorized: [401]
17
- },
18
- responseDataKey: "data",
19
- responseMessageKey: "message",
20
- isTransformResponse: true,
21
- isShowSuccessMessage: false,
22
- successDefaultMessage: "操作成功",
23
- isShowErrorMessage: true,
24
- errorDefaultMessage: "服务异常",
25
- requestAdapter: adapterFetch()
26
- };
27
- const mergeOption = deepMergeObject(defaultOption, option);
5
+ const defaultRequestOption = {
6
+ baseUrl: "/",
7
+ timeout: void 0,
8
+ statusMap: {
9
+ success: 200,
10
+ unAuthorized: 401
11
+ },
12
+ codeMap: {
13
+ success: [200],
14
+ unAuthorized: [401]
15
+ },
16
+ responseCodeKey: "code",
17
+ responseDataKey: "data",
18
+ responseMessageKey: "message",
19
+ isWrapped: true,
20
+ isTransformResponse: true,
21
+ isShowSuccessMessage: false,
22
+ successDefaultMessage: "操作成功",
23
+ isShowErrorMessage: true,
24
+ errorDefaultMessage: "服务异常",
25
+ cacheFor: null,
26
+ cacheLogger: true,
27
+ requestAdapter: adapterFetch()
28
+ };
29
+ function getMethodMeta(method) {
30
+ const methodRecord = method;
31
+ return methodRecord?.config?.meta ?? methodRecord?.meta ?? {};
32
+ }
33
+ function getMetaFlag(meta, key, fallback) {
34
+ const value = meta[key];
35
+ return typeof value === "boolean" ? value : fallback;
36
+ }
37
+ function isMatchedStatus(status, matcher, response) {
38
+ if (matcher === void 0) return status >= 200 && status < 300;
39
+ if (typeof matcher === "function") return matcher(status, response);
40
+ return Array.isArray(matcher) ? matcher.includes(status) : matcher === status;
41
+ }
42
+ function isMatchedCode(code, matcher) {
43
+ if (!matcher?.length) return true;
44
+ return matcher.some((item) => String(item) === String(code));
45
+ }
46
+ function getResponseStatus(response) {
47
+ const responseRecord = response;
48
+ const status = responseRecord.statusCode ?? responseRecord.status;
49
+ return typeof status === "number" ? status : Number(status);
50
+ }
51
+ function getResponseMessage(data, messageKey, defaultMessage) {
52
+ if (!isPlainObject(data)) return defaultMessage;
53
+ const message = data[messageKey] ?? data.message ?? data.msg;
54
+ if (typeof message === "string") return message || defaultMessage;
55
+ if (typeof message === "number") return String(message);
56
+ return defaultMessage;
57
+ }
58
+ function getResponseField(data, key) {
59
+ return isPlainObject(data) ? data[key] : void 0;
60
+ }
61
+ async function parseFetchResponse(response) {
62
+ if (response.status === 204) return void 0;
63
+ const reader = typeof response.clone === "function" ? response.clone() : response;
64
+ const contentType = getHeaderValue(response.headers, "content-type");
65
+ if (contentType.includes("application/json") && typeof reader.json === "function") return reader.json();
66
+ if (contentType.startsWith("text/") && typeof reader.text === "function") return tryParseJsonString(await reader.text());
67
+ if (typeof reader.json === "function") try {
68
+ return await reader.json();
69
+ } catch {}
70
+ if (typeof reader.text === "function") return tryParseJsonString(await reader.text());
71
+ }
72
+ function getHeaderValue(headers, key) {
73
+ if (!headers) return "";
74
+ if (typeof Headers !== "undefined" && headers instanceof Headers) return headers.get(key) ?? "";
75
+ const headerRecord = headers;
76
+ const value = headerRecord[key] ?? headerRecord[key.toLowerCase()] ?? headerRecord[key.toUpperCase()];
77
+ return typeof value === "string" ? value : "";
78
+ }
79
+ async function getResponseData(response) {
80
+ const responseRecord = response;
81
+ if ("data" in responseRecord && !isReadableStream(responseRecord.body)) return tryParseJsonString(responseRecord.data);
82
+ if (isReadableStream(responseRecord.body) || typeof responseRecord.json === "function" || typeof responseRecord.text === "function") return parseFetchResponse(responseRecord);
83
+ return response;
84
+ }
85
+ async function resolveHeaderValue(value) {
86
+ const resolved = typeof value === "function" ? await value() : value;
87
+ if (resolved === null || resolved === void 0) return void 0;
88
+ return String(resolved);
89
+ }
90
+ function setHeader(target, key, value) {
91
+ if (typeof Headers !== "undefined" && target instanceof Headers) {
92
+ target.set(key, value);
93
+ return;
94
+ }
95
+ if (Array.isArray(target)) {
96
+ target.push([key, value]);
97
+ return;
98
+ }
99
+ target[key] = value;
100
+ }
101
+ function resolveConfig(option) {
102
+ return deepMergeObject(defaultRequestOption, option);
103
+ }
104
+ function createInstance(option = {}) {
105
+ const config = resolveConfig(option);
28
106
  return createAlova({
29
- baseURL: mergeOption.baseUrl,
30
- timeout: mergeOption.timeout,
31
- statesHook: mergeOption?.statesHook,
32
- requestAdapter: mergeOption.requestAdapter,
107
+ baseURL: config.baseUrl,
108
+ timeout: config.timeout,
109
+ cacheFor: config.cacheFor,
110
+ cacheLogger: config.cacheLogger,
111
+ statesHook: config.statesHook,
112
+ requestAdapter: config.requestAdapter,
113
+ l1Cache: config.l1Cache,
114
+ l2Cache: config.l2Cache ?? config.storageAdapter,
33
115
  beforeRequest: async (method) => {
34
- for (const [key, value] of Object.entries(option?.commonHeaders ?? {})) method.config.headers[key] = typeof value === "function" ? value() : value;
116
+ const methodConfig = method.config;
117
+ const headers = methodConfig.headers ?? {};
118
+ methodConfig.headers = headers;
119
+ for (const [key, value] of Object.entries(config.commonHeaders ?? {})) {
120
+ const resolvedValue = await resolveHeaderValue(value);
121
+ if (resolvedValue !== void 0) setHeader(headers, key, resolvedValue);
122
+ }
35
123
  },
36
124
  responded: {
37
- onSuccess: async (response) => {
38
- if (!mergeOption?.isTransformResponse) return response;
39
- const { status } = response;
40
- const data = response?.body && isReadableStream(response.body) ? await response.json() : response.data;
41
- if (status !== mergeOption.statusMap?.success) {
42
- if (mergeOption?.statusMap?.unAuthorized === status) mergeOption?.unAuthorizedResponseFunc?.();
125
+ onSuccess: async (response, method) => {
126
+ const meta = getMethodMeta(method);
127
+ const shouldTransform = getMetaFlag(meta, "isTransformResponse", config.isTransformResponse);
128
+ const showSuccess = getMetaFlag(meta, "isShowSuccessMessage", config.isShowSuccessMessage);
129
+ const showError = getMetaFlag(meta, "isShowErrorMessage", config.isShowErrorMessage);
130
+ const isWrapped = getMetaFlag(meta, "isWrapped", config.isWrapped);
131
+ if (!shouldTransform) return response;
132
+ const status = getResponseStatus(response);
133
+ const data = await getResponseData(response);
134
+ if (!isMatchedStatus(status, config.statusMap.success, response)) {
135
+ if (isMatchedStatus(status, config.statusMap.unAuthorized, response)) config.unAuthorizedResponseFunc?.();
136
+ if (showError) config.errorMessageFunc?.(getResponseMessage(data, config.responseMessageKey, config.errorDefaultMessage));
43
137
  return Promise.reject(response);
44
138
  }
45
- const { responseDataKey, codeMap, isShowSuccessMessage, responseMessageKey, isShowErrorMessage } = mergeOption;
46
- const { code, [responseDataKey]: responseData, [responseMessageKey]: responseMessage } = data;
47
- if (!codeMap?.success?.includes(+code)) {
48
- if (codeMap?.unAuthorized?.includes(+code)) {
49
- mergeOption?.unAuthorizedResponseFunc?.();
50
- return Promise.reject(response);
51
- }
52
- const errorMessage = data[responseMessageKey] ?? mergeOption.errorDefaultMessage;
53
- if (isShowErrorMessage) mergeOption?.errorMessageFunc?.(errorMessage);
139
+ if (!isWrapped) {
140
+ if (showSuccess) config.successMessageFunc?.(config.successDefaultMessage);
141
+ return data;
142
+ }
143
+ const code = getResponseField(data, config.responseCodeKey);
144
+ const responseData = getResponseField(data, config.responseDataKey);
145
+ const responseMessage = getResponseMessage(data, config.responseMessageKey, config.successDefaultMessage);
146
+ if (!isMatchedCode(code, config.codeMap.success)) {
147
+ if (isMatchedCode(code, config.codeMap.unAuthorized)) config.unAuthorizedResponseFunc?.();
148
+ if (showError) config.errorMessageFunc?.(getResponseMessage(data, config.responseMessageKey, config.errorDefaultMessage));
54
149
  return Promise.reject(response);
55
150
  }
56
- if (isShowSuccessMessage) mergeOption?.successMessageFunc?.(responseMessage ?? mergeOption.successDefaultMessage);
151
+ if (showSuccess) config.successMessageFunc?.(responseMessage);
57
152
  return responseData;
58
153
  },
59
- onError: (error) => {
60
- if (mergeOption?.isShowErrorMessage) mergeOption.errorMessageFunc?.(error.response?.data?.message ?? mergeOption?.errorDefaultMessage);
154
+ onError: (error, method) => {
155
+ if (getMetaFlag(getMethodMeta(method), "isShowErrorMessage", config.isShowErrorMessage)) config.errorMessageFunc?.(error instanceof Error ? error.message : config.errorDefaultMessage);
156
+ return Promise.reject(error);
61
157
  }
62
158
  }
63
159
  });
64
- };
65
- const createDualCallInstance = (baseConfig) => {
160
+ }
161
+ function createDualCallInstance(baseConfig) {
66
162
  const defaultInstance = createInstance(baseConfig);
67
- const dualInstance = (option) => {
68
- if (option) {
69
- const mergedConfig = {
70
- ...baseConfig,
71
- ...option
72
- };
73
- return createInstance(mergedConfig);
74
- }
75
- return defaultInstance;
76
- };
163
+ const dualInstance = ((option) => {
164
+ if (!option) return defaultInstance;
165
+ return createInstance(deepMergeObject(baseConfig, option));
166
+ });
167
+ Object.assign(dualInstance, defaultInstance);
77
168
  dualInstance.Get = defaultInstance.Get.bind(defaultInstance);
78
169
  dualInstance.Post = defaultInstance.Post.bind(defaultInstance);
79
170
  dualInstance.Put = defaultInstance.Put.bind(defaultInstance);
@@ -83,7 +174,6 @@ const createDualCallInstance = (baseConfig) => {
83
174
  dualInstance.Options = defaultInstance.Options.bind(defaultInstance);
84
175
  dualInstance.Request = defaultInstance.Request.bind(defaultInstance);
85
176
  return dualInstance;
86
- };
87
-
177
+ }
88
178
  //#endregion
89
- export { createDualCallInstance, createInstance };
179
+ export { createDualCallInstance, createInstance };
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "@bubblesjs/request",
3
- "version": "0.0.2",
3
+ "version": "0.0.6",
4
4
  "type": "module",
5
5
  "private": false,
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/435012357/bubblesjs.git"
9
+ },
10
+ "bugs": {
11
+ "url": "git+https://github.com/435012357/bubblesjs/issues"
12
+ },
13
+ "types": "./dist/index.d.ts",
6
14
  "exports": {
7
15
  ".": {
8
16
  "types": "./dist/index.d.ts",
@@ -14,23 +22,18 @@
14
22
  "dist"
15
23
  ],
16
24
  "dependencies": {
17
- "@bubblesjs/utils": "^0.0.7"
25
+ "@bubblesjs/utils": "^0.0.9"
18
26
  },
19
27
  "peerDependencies": {
20
- "alova": "^3.3.4",
21
- "axios": "^1.12.1"
28
+ "alova": "^3.5.1"
22
29
  },
23
30
  "devDependencies": {
24
- "axios": "^1.12.1",
25
- "tsdown": "^0.14.1",
26
- "vitest": "^3.2.4"
31
+ "tsdown": "^0.22.2",
32
+ "vitest": "^4.1.8"
27
33
  },
28
34
  "peerDependenciesMeta": {
29
35
  "alova": {
30
36
  "optional": true
31
- },
32
- "axios": {
33
- "optional": true
34
37
  }
35
38
  },
36
39
  "publishConfig": {