kodzero-front-sdk-alfa 0.0.4 → 0.0.5

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 (72) hide show
  1. package/dist/Kodzero.d.ts +1 -0
  2. package/dist/Kodzero.js +7 -3
  3. package/dist/__mocks__/fluid-fetch.d.ts +1 -0
  4. package/dist/__mocks__/fluid-fetch.js +23 -0
  5. package/dist/__mocks__/validno.d.ts +5 -0
  6. package/dist/__mocks__/validno.js +9 -0
  7. package/dist/auth/base.js +8 -5
  8. package/dist/auth/email.js +62 -60
  9. package/dist/auth/index.js +3 -0
  10. package/dist/auth/tokens.js +2 -0
  11. package/dist/errors/KodzeroApiError.js +3 -0
  12. package/dist/errors/KodzeroValidationError.js +1 -0
  13. package/dist/index.d.ts +2 -1
  14. package/dist/index.js +1 -48
  15. package/dist/model/BaseModel.d.ts +2 -2
  16. package/dist/model/BaseModel.js +25 -28
  17. package/dist/model/PaginatedResult.d.ts +28 -0
  18. package/dist/model/PaginatedResult.js +49 -0
  19. package/dist/model/createModel.d.ts +3 -1
  20. package/dist/model/createModel.js +145 -147
  21. package/dist/schemas/baseAuth.js +13 -13
  22. package/dist/schemas/baseModel.js +20 -20
  23. package/dist/tsconfig.tsbuildinfo +1 -1
  24. package/dist/utils/buildURL.js +3 -1
  25. package/dist/utils/validateApiResponse.js +1 -1
  26. package/jest.config.ts +23 -19
  27. package/package.json +6 -5
  28. package/src/__mocks__/fluid-fetch.ts +35 -0
  29. package/src/__mocks__/validno.ts +12 -0
  30. package/src/__tests__/Kodzero.test.ts +9 -0
  31. package/src/__tests__/utils/buildURL.test.ts +18 -0
  32. package/src/index.ts +3 -0
  33. package/src/model/BaseModel.ts +10 -12
  34. package/src/model/PaginatedResult.ts +81 -0
  35. package/src/model/createModel.ts +39 -15
  36. package/src/schemas/baseAuth.ts +2 -1
  37. package/src/schemas/baseModel.ts +1 -1
  38. package/src/tsconfig.json +9 -8
  39. package/src/utils/buildURL.ts +2 -1
  40. package/dist/fetcher/InterceptorManager.d.ts +0 -9
  41. package/dist/fetcher/InterceptorManager.js +0 -42
  42. package/dist/fetcher/MiddlewareManager.d.ts +0 -9
  43. package/dist/fetcher/MiddlewareManager.js +0 -42
  44. package/dist/fetcher/index.d.ts +0 -77
  45. package/dist/fetcher/index.js +0 -194
  46. package/dist/model/baseModelOptionsSchema.d.ts +0 -2
  47. package/dist/model/baseModelOptionsSchema.js +0 -10
  48. package/dist/model/configSchema.d.ts +0 -0
  49. package/dist/model/configSchema.js +0 -1
  50. package/dist/model/errors/KodzeroApiError.d.ts +0 -7
  51. package/dist/model/errors/KodzeroApiError.js +0 -10
  52. package/dist/model/modelFactory.d.ts +0 -50
  53. package/dist/model/modelFactory.js +0 -41
  54. package/dist/model/modelSchema.d.ts +0 -0
  55. package/dist/model/modelSchema.js +0 -1
  56. package/dist/model/schemas/baseModel.d.ts +0 -6
  57. package/dist/model/schemas/baseModel.js +0 -25
  58. package/dist/model/schemas/baseModelOptionsSchema.d.ts +0 -2
  59. package/dist/model/schemas/baseModelOptionsSchema.js +0 -10
  60. package/dist/model/statics/getAll.d.ts +0 -2
  61. package/dist/model/statics/getAll.js +0 -4
  62. package/dist/model/utils/processUrl.d.ts +0 -2
  63. package/dist/model/utils/processUrl.js +0 -7
  64. package/dist/model/utils/validateApiResponse.d.ts +0 -2
  65. package/dist/model/utils/validateApiResponse.js +0 -14
  66. package/dist/schemas/baseModel copy.d.ts +0 -6
  67. package/dist/schemas/baseModel copy.js +0 -25
  68. package/dist/utils/buildURL_rename.d.ts +0 -2
  69. package/dist/utils/buildURL_rename.js +0 -7
  70. package/dist/utils/processUrl.d.ts +0 -2
  71. package/dist/utils/processUrl.js +0 -7
  72. /package/{.eslintrc.cjs → eslintrc.cjs} +0 -0
@@ -1,9 +1,10 @@
1
1
  import Schema from "validno";
2
2
  import FluidFetch from "fluid-fetch";
3
+
3
4
  import constants from "./constants.js";
4
- import validateApiResponse from "../utils/validateApiResponse.js";
5
- import BaseModelSchema from "../schemas/baseModel.js";
6
5
  import buildURL from "../utils/buildURL.js";
6
+ import BaseModelSchema from "../schemas/baseModel.js";
7
+ import validateApiResponse from "../utils/validateApiResponse.js";
7
8
 
8
9
  export interface ModelOptions {
9
10
  host: string
@@ -19,7 +20,7 @@ class BaseModel<T extends { _id?: string }> {
19
20
  collection: string
20
21
  modelData: T = {} as T
21
22
  schema?: typeof Schema
22
- api: typeof FluidFetch
23
+ apiClient: typeof FluidFetch
23
24
 
24
25
  id: string | null;
25
26
 
@@ -27,13 +28,13 @@ class BaseModel<T extends { _id?: string }> {
27
28
  static collection: string
28
29
  static api: typeof FluidFetch
29
30
 
30
- constructor(options: ModelOptions, api: typeof FluidFetch) {
31
+ constructor(options: ModelOptions, apiClient: typeof FluidFetch) {
31
32
  BaseModelSchema.validateOrThrow(options);
32
33
 
33
34
  this.host = options.host
34
35
  this.collection = options.collection
35
36
  this.schema = options.schema ? new Schema({...options.schema}) : null
36
- this.api = api
37
+ this.apiClient = apiClient
37
38
  this.id = null;
38
39
  }
39
40
 
@@ -147,7 +148,7 @@ class BaseModel<T extends { _id?: string }> {
147
148
 
148
149
  const updateUrl = buildURL(this.host, this.collection, this.id)
149
150
 
150
- const response = await this.api.patch(updateUrl, this._dataWithoutId())
151
+ const response = await this.apiClient.patch(updateUrl, this._dataWithoutId())
151
152
  .headers({ 'Content-Type': 'application/json' });
152
153
 
153
154
  await this._handleApiError(response);
@@ -167,8 +168,7 @@ class BaseModel<T extends { _id?: string }> {
167
168
  }
168
169
 
169
170
  const deleteUrl = buildURL(this.host, this.collection, this.id);
170
-
171
- const response = await this.api.delete(deleteUrl);
171
+ const response = await this.apiClient.delete(deleteUrl);
172
172
  await this._handleApiError(response);
173
173
 
174
174
  this._setId(null);
@@ -182,13 +182,11 @@ class BaseModel<T extends { _id?: string }> {
182
182
  */
183
183
  async create(): Promise<T> {
184
184
  const createUrl = buildURL(this.host, this.collection)
185
-
186
- const response = await this.api.post(createUrl, this._dataWithoutId())
185
+ const response = await this.apiClient.post(createUrl, this._dataWithoutId())
187
186
  .headers({ 'Content-Type': 'application/json' });
188
-
189
187
  await this._handleApiError(response);
190
- const json = await response.json();
191
188
 
189
+ const json = await response.json();
192
190
  this._setModelData(json.result);
193
191
 
194
192
  return this.modelData
@@ -0,0 +1,81 @@
1
+ import { FindManyOptions } from "./createModel.js"
2
+
3
+ interface PaginationState {
4
+ skip: number,
5
+ limit: number,
6
+ page: number,
7
+ total: number,
8
+ totalPages: number,
9
+ left: number
10
+ }
11
+
12
+ interface PaginationResultInput<T> {
13
+ data: T[],
14
+ state: PaginationState,
15
+ options: FindManyOptions | {},
16
+ findManyFunction: Function
17
+ }
18
+
19
+ class PaginatedResult<T = {}> {
20
+ state: PaginationState
21
+ data: Array<T>
22
+ options: FindManyOptions | {}
23
+ private findManyFunction: Function
24
+
25
+ constructor(input: PaginationResultInput<T>) {
26
+ const {findManyFunction, state, data, options} = input
27
+
28
+ this.options = options
29
+ this.findManyFunction = findManyFunction
30
+
31
+ this.state = {
32
+ skip: state.skip || 0,
33
+ limit: state.limit || 0,
34
+ page: state.page || 0,
35
+ total: state.total || 0,
36
+ totalPages: state.totalPages || 0,
37
+ left: state.left || 0
38
+ }
39
+
40
+ this.data = data
41
+ }
42
+
43
+ async next(): Promise<PaginatedResult<T>> {
44
+ this.state.page++;
45
+
46
+ const result = await this.findManyFunction(this.options, this.state.page, this.state.limit);
47
+ this.data = result.data;
48
+
49
+ return this;
50
+ }
51
+
52
+ async previous(): Promise<PaginatedResult<T>> {
53
+ if (this.state.page === 1) throw new Error('Page cannot be lower than 1')
54
+
55
+ this.state.page--;
56
+ const result = await this.findManyFunction(this.options, this.state.page, this.state.limit);
57
+ this.data = result.data
58
+
59
+ return this;
60
+ }
61
+
62
+ async page(pageNumber: number) {
63
+ if (pageNumber < 1) throw new Error('Page cannot be lower than 1')
64
+
65
+ this.state.page = pageNumber
66
+ const result = this.findManyFunction(this.options, this.state.page, this.state.limit);
67
+ this.data = result.data
68
+
69
+ return this;
70
+ }
71
+
72
+ hasNext(): boolean {
73
+ return this.state.page < this.state.totalPages
74
+ }
75
+
76
+ hasPrevious(): boolean {
77
+ return this.state.page > 1
78
+ }
79
+ }
80
+
81
+ export default PaginatedResult
@@ -4,6 +4,7 @@ import {KzResponseFindMany } from '../types/responses.js'
4
4
  import validateApiResponse from '../utils/validateApiResponse.js'
5
5
  import buildURL from '../utils/buildURL.js'
6
6
  import constants from './constants.js'
7
+ import PaginatedResult from './PaginatedResult.js'
7
8
 
8
9
  export interface FindManyOptions {
9
10
  page: number
@@ -19,11 +20,11 @@ export interface FindManyOptions {
19
20
  const createModel = <
20
21
  T extends { _id?: string },
21
22
  M = {}
22
- >(options: ModelOptions, api: typeof FluidFetch) => {
23
+ >(options: ModelOptions, apiClient: typeof FluidFetch) => {
23
24
  const Model = class extends BaseModel<T> {
24
25
  static host = options.host
25
26
  static collection = options.collection
26
- static api = api
27
+ static apiClient = apiClient
27
28
 
28
29
  static async _handleApiError(response: Response) {
29
30
  return validateApiResponse(response)
@@ -62,7 +63,7 @@ const createModel = <
62
63
 
63
64
  const getUrl = buildURL(Model.host, Model.collection, id)
64
65
 
65
- const response = await Model.api.get(getUrl);
66
+ const response = await Model.apiClient.get(getUrl);
66
67
  await Model._handleApiError(response);
67
68
 
68
69
  const data = await response.json();
@@ -74,18 +75,40 @@ const createModel = <
74
75
 
75
76
  const params = {...options} as Record<string, any>;
76
77
 
77
- const response = await Model.api.get(getUrl).params(params);
78
+ const response = await Model.apiClient.get(getUrl).params(params);
78
79
  await Model._handleApiError(response);
79
80
 
80
81
  const data: KzResponseFindMany<T> = await response.json();
81
82
  return data.result.found;
82
83
  }
83
84
 
85
+ static async findManyPaginated(
86
+ options: FindManyOptions | {} = {},
87
+ page: number = 1,
88
+ perPage: number = 25
89
+ ): Promise<any> {
90
+ if (!page || page < 1) throw new Error('Page number must be greater than 0');
91
+
92
+ const getUrl = buildURL(Model.host, Model.collection)
93
+ const params = {...options, page, perPage} as Record<string, any>;
94
+ const response = await Model.apiClient.get(getUrl).params(params);
95
+ await Model._handleApiError(response);
96
+
97
+ const data: KzResponseFindMany<T> = await response.json();
98
+
99
+ return new PaginatedResult({
100
+ data: data.result.found,
101
+ state: data.result,
102
+ options,
103
+ findManyFunction: Model.findManyPaginated
104
+ })
105
+ }
106
+
84
107
  static async create(data: T): Promise<T> {
85
108
  const createUrl = buildURL(Model.host, Model.collection)
86
109
  const {_id, ...dataWithoutId} = data as T & {_id?: string};
87
110
 
88
- const response = await Model.api.post(createUrl)
111
+ const response = await Model.apiClient.post(createUrl)
89
112
  .body(dataWithoutId)
90
113
  .headers({
91
114
  'Content-Type': 'application/json'
@@ -109,7 +132,7 @@ const createModel = <
109
132
  return rest;
110
133
  });
111
134
 
112
- const response = await Model.api.post(createUrl)
135
+ const response = await Model.apiClient.post(createUrl)
113
136
  .body(dataWithoutId)
114
137
  .headers({
115
138
  'Content-Type': 'application/json'
@@ -127,7 +150,7 @@ const createModel = <
127
150
 
128
151
  const updateUrl = buildURL(Model.host, Model.collection, id)
129
152
  const {_id, ...dataWithoutId} = data as Partial<T> & {_id?: string};
130
- const response = await Model.api.patch(updateUrl)
153
+ const response = await Model.apiClient.patch(updateUrl)
131
154
  .body(dataWithoutId)
132
155
  .headers({ 'Content-Type': 'application/json' });
133
156
 
@@ -148,7 +171,7 @@ const createModel = <
148
171
 
149
172
  const updateUrl = buildURL(Model.host, Model.collection) + '/batch'
150
173
 
151
- const response = await Model.api.patch(updateUrl)
174
+ const response = await Model.apiClient.patch(updateUrl)
152
175
  .body(updates)
153
176
  .headers({ 'Content-Type': 'application/json' });
154
177
 
@@ -163,7 +186,7 @@ const createModel = <
163
186
 
164
187
  const deleteUrl = buildURL(Model.host, Model.collection, id)
165
188
 
166
- const response = await Model.api.delete(deleteUrl);
189
+ const response = await Model.apiClient.delete(deleteUrl);
167
190
  await Model._handleApiError(response);
168
191
 
169
192
  const json = await response.json();
@@ -171,13 +194,11 @@ const createModel = <
171
194
  }
172
195
 
173
196
  static async deleteMany(ids: string[]): Promise<Record<string, boolean>> {
174
- if (!ids || ids.length === 0) {
175
- throw new Error(constants.RequiresIdsArray);
176
- }
197
+ if (!ids || ids.length === 0) throw new Error(constants.RequiresIdsArray);
177
198
 
178
199
  const deleteUrl = buildURL(Model.host, Model.collection) + '/batch'
179
200
 
180
- const response = await Model.api.delete(deleteUrl)
201
+ const response = await Model.apiClient.delete(deleteUrl)
181
202
  .body({ ids })
182
203
  .headers({ 'Content-Type': 'application/json' });
183
204
 
@@ -188,13 +209,15 @@ const createModel = <
188
209
  }
189
210
 
190
211
  static async distinct(fields: string[], filter?: Record<string, any>): Promise<string[]> {
212
+ throw new Error('Distinct method is disabled in this SDK version'); // temporary disable
213
+
191
214
  if (!fields || fields.length === 0) {
192
215
  throw new Error(constants.DistinctRequiresFieldsArray);
193
216
  }
194
217
 
195
218
  const distinctUrl = buildURL(Model.host, Model.collection, 'distinct')
196
219
 
197
- const response = await Model.api.post(distinctUrl)
220
+ const response = await Model.apiClient.get(distinctUrl)
198
221
  .params({ fields: fields.join(','), filter: filter ? JSON.stringify(filter) : undefined })
199
222
  .headers({ 'Content-Type': 'application/json' });
200
223
 
@@ -205,7 +228,7 @@ const createModel = <
205
228
  }
206
229
 
207
230
  constructor(data: T) {
208
- super(options, api)
231
+ super(options, apiClient)
209
232
 
210
233
  this.modelData = {...data, _id: null}
211
234
  this.id = null;
@@ -220,6 +243,7 @@ const createModel = <
220
243
  registerMethod<K extends keyof M>(name: K, fn: M[K]): void;
221
244
  find(id: string): Promise<T>;
222
245
  findMany(options?: FindManyOptions | {}): Promise<T[]>;
246
+ findManyPaginated(options?: FindManyOptions | {}, page?: number, perPage?: number): Promise<PaginatedResult<T>>;
223
247
  create(data: T): Promise<T>;
224
248
  createMany(data: T[]): Promise<T[]>;
225
249
  update(id: string, data: Partial<T>): Promise<T>;
@@ -1,6 +1,7 @@
1
1
  import Schema from 'validno'
2
2
  import KodzeroValidationError from '../errors/KodzeroValidationError.js';
3
3
 
4
+ // TODO: сделать класс конструктор для таких реализаций?
4
5
  class BaseAuthSchema {
5
6
  // Validation schema for BaseAuth class constructor options
6
7
  static schema = new Schema({
@@ -16,7 +17,7 @@ class BaseAuthSchema {
16
17
 
17
18
  if (!validation.ok) {
18
19
  throw new KodzeroValidationError(
19
- 'Invalid auth options: ' + validation.failed.join(', '),
20
+ 'Invalid auth options: ' + validation.failed.join(', '), // TODO: to constants
20
21
  validation.errors
21
22
  );
22
23
  }
@@ -23,7 +23,7 @@ class BaseModelSchema {
23
23
 
24
24
  if (!validation.ok) {
25
25
  throw new KodzeroValidationError(
26
- 'Invalid model options: ' + validation.failed.join(', '),
26
+ 'Invalid model options: ' + validation.failed.join(', '), // TODO: to constants
27
27
  validation.errors
28
28
  );
29
29
  }
package/src/tsconfig.json CHANGED
@@ -11,7 +11,7 @@
11
11
  // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
12
 
13
13
  /* Language and Environment */
14
- "target": "ES2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
14
+ "target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
15
  // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
16
  // "jsx": "preserve", /* Specify what JSX code is generated. */
17
17
  // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
@@ -25,9 +25,9 @@
25
25
  // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
26
 
27
27
  /* Modules */
28
- "module": "ES2022", /* Specify what module code is generated. */
28
+ "module": "nodenext", /* Specify what module code is generated. */
29
29
  "rootDir": "../src/", /* Specify the root folder within your source files. */
30
- "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ "moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
31
31
  // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
32
  // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
33
  // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
@@ -70,11 +70,10 @@
70
70
 
71
71
  /* Interop Constraints */
72
72
  // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
73
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
73
+ "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
74
74
  "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
75
75
  // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
76
76
  "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
77
-
78
77
  /* Type Checking */
79
78
  "strict": true, /* Enable all strict type-checking options. */
80
79
  // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
@@ -95,9 +94,11 @@
95
94
  // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
96
95
  // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
97
96
  // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
98
-
99
97
  /* Completeness */
100
98
  // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
102
- }
99
+ },
100
+ "exclude": [
101
+ "**/*.test.ts",
102
+ "**/__tests__/**"
103
+ ]
103
104
  }
@@ -1,5 +1,6 @@
1
1
  const buildURL = (baseUrl: string, collection: string, id?: string): string => {
2
- let url = `${baseUrl}/${collection}`;
2
+ let url = `${baseUrl}`
3
+ if (collection) url += `/${collection}`;
3
4
  if (id) url += `/${id}`;
4
5
 
5
6
  return url.replace(/\/+/g, '/').replace(':/', '://');
@@ -1,9 +0,0 @@
1
- declare class MiddlewareManager<T> {
2
- private handlers;
3
- private idCounter;
4
- use(fulfilled: (value: T) => Promise<T> | T, rejected?: (error: any) => any): number;
5
- eject(id: number): void;
6
- clear(): void;
7
- runMiddlewares(value: T): Promise<T>;
8
- }
9
- export default MiddlewareManager;
@@ -1,42 +0,0 @@
1
- class MiddlewareManager {
2
- constructor() {
3
- this.handlers = [];
4
- this.idCounter = 0;
5
- }
6
- use(fulfilled, rejected) {
7
- const id = this.idCounter++;
8
- this.handlers.push({
9
- fulfilled,
10
- rejected,
11
- id
12
- });
13
- return id;
14
- }
15
- eject(id) {
16
- const index = this.handlers.findIndex(handler => handler.id === id);
17
- if (index !== -1) {
18
- this.handlers.splice(index, 1);
19
- }
20
- }
21
- clear() {
22
- this.handlers = [];
23
- }
24
- async runMiddlewares(value) {
25
- let result = value;
26
- for (const handler of this.handlers) {
27
- try {
28
- result = await handler.fulfilled(result);
29
- }
30
- catch (error) {
31
- if (handler.rejected) {
32
- result = await handler.rejected(error);
33
- }
34
- else {
35
- throw error;
36
- }
37
- }
38
- }
39
- return result;
40
- }
41
- }
42
- export default MiddlewareManager;
@@ -1,9 +0,0 @@
1
- declare class MiddlewareManager<T> {
2
- private handlers;
3
- private idCounter;
4
- use(fulfilled: (value: T) => Promise<T> | T, rejected?: (error: any) => any): number;
5
- eject(id: number): void;
6
- clear(): void;
7
- runMiddlewares(value: T): Promise<T>;
8
- }
9
- export default MiddlewareManager;
@@ -1,42 +0,0 @@
1
- class MiddlewareManager {
2
- constructor() {
3
- this.handlers = [];
4
- this.idCounter = 0;
5
- }
6
- use(fulfilled, rejected) {
7
- const id = this.idCounter++;
8
- this.handlers.push({
9
- fulfilled,
10
- rejected,
11
- id
12
- });
13
- return id;
14
- }
15
- eject(id) {
16
- const index = this.handlers.findIndex(handler => handler.id === id);
17
- if (index !== -1) {
18
- this.handlers.splice(index, 1);
19
- }
20
- }
21
- clear() {
22
- this.handlers = [];
23
- }
24
- async runMiddlewares(value) {
25
- let result = value;
26
- for (const handler of this.handlers) {
27
- try {
28
- result = await handler.fulfilled(result);
29
- }
30
- catch (error) {
31
- if (handler.rejected) {
32
- result = await handler.rejected(error);
33
- }
34
- else {
35
- throw error;
36
- }
37
- }
38
- }
39
- return result;
40
- }
41
- }
42
- export default MiddlewareManager;
@@ -1,77 +0,0 @@
1
- import MiddlewareManager from './MiddlewareManager.js';
2
- type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
3
- declare class TimeoutError extends Error {
4
- constructor(message: string);
5
- }
6
- interface RequestConfig {
7
- headers?: Record<string, string>;
8
- params?: Record<string, string | number | boolean>;
9
- cache?: boolean | number;
10
- timeout?: number;
11
- }
12
- interface RequestMiddleware {
13
- (request: Request): Promise<Request> | Request;
14
- }
15
- interface ResponseMiddleware {
16
- (response: Response): Promise<Response> | Response;
17
- }
18
- interface Middlewares {
19
- request: RequestMiddleware[];
20
- response: ResponseMiddleware[];
21
- }
22
- interface Request {
23
- method: HttpMethod;
24
- url: string;
25
- data: any | null;
26
- headers: Record<string, string>;
27
- params: Record<string, string | number | boolean>;
28
- cache?: boolean | number;
29
- timeout?: number;
30
- abortController: AbortController;
31
- }
32
- declare class FluidFetch {
33
- private cache;
34
- private pendingRequests;
35
- middlewares: {
36
- request: MiddlewareManager<Request>;
37
- response: MiddlewareManager<Response>;
38
- };
39
- interceptors: Middlewares & {
40
- request: MiddlewareManager<Request>;
41
- response: MiddlewareManager<Response>;
42
- };
43
- constructor();
44
- get<T = any>(url: string, config?: RequestConfig): FluidFetchRequest<T>;
45
- post<T = any>(url: string, data?: any, config?: RequestConfig): FluidFetchRequest<T>;
46
- put<T = any>(url: string, data?: any, config?: RequestConfig): FluidFetchRequest<T>;
47
- delete<T = any>(url: string, config?: RequestConfig): FluidFetchRequest<T>;
48
- private _createRequest;
49
- _getCacheKey(request: Request): string;
50
- _buildUrl(url: string, params: Record<string, string | number | boolean> | undefined): string;
51
- getCachedResponse(cacheKey: string): Response | undefined;
52
- getPendingRequest(cacheKey: string): AbortController | undefined;
53
- registerPendingRequest(cacheKey: string, controller: AbortController): void;
54
- removePendingRequest(cacheKey: string): void;
55
- cacheResponse(cacheKey: string, response: Response, ttl?: number): void;
56
- clearRequestMiddlewares(): void;
57
- clearResponseMiddlewares(): void;
58
- clearRequestInterceptors(): void;
59
- clearResponseInterceptors(): void;
60
- }
61
- declare class FluidFetchRequest<T = any> implements PromiseLike<Response> {
62
- private fluidFetch;
63
- private request;
64
- private promise;
65
- constructor(fluidFetch: FluidFetch, request: Request);
66
- headers(headers: Record<string, string>): FluidFetchRequest<T>;
67
- params(params: Record<string, string | number | boolean>): FluidFetchRequest<T>;
68
- body(data: any): FluidFetchRequest<T>;
69
- cache(ttl: boolean | number): FluidFetchRequest<T>;
70
- timeout(ms: number): FluidFetchRequest<T>;
71
- cancel(): FluidFetchRequest<T>;
72
- then<TResult1 = Response, TResult2 = never>(onFulfilled?: ((value: Response) => TResult1 | PromiseLike<TResult1>) | undefined | null, onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
73
- catch<TResult = never>(onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): PromiseLike<Response | TResult>;
74
- private _executeRequest;
75
- }
76
- export { TimeoutError, MiddlewareManager, RequestMiddleware, ResponseMiddleware };
77
- export default FluidFetch;