@hyper-fetch/core 1.7.1 → 2.1.0

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 (58) hide show
  1. package/README.md +15 -13
  2. package/dist/builder/builder.d.ts +17 -18
  3. package/dist/builder/builder.types.d.ts +14 -18
  4. package/dist/builder/builder.utils.d.ts +3 -3
  5. package/dist/cache/cache.d.ts +5 -5
  6. package/dist/cache/cache.events.d.ts +1 -1
  7. package/dist/cache/cache.types.d.ts +9 -9
  8. package/dist/cache/cache.utils.d.ts +2 -2
  9. package/dist/client/fetch.client.bindings.d.ts +5 -5
  10. package/dist/client/fetch.client.browser.d.ts +2 -0
  11. package/dist/client/fetch.client.d.ts +1 -1
  12. package/dist/client/fetch.client.server.d.ts +2 -0
  13. package/dist/client/fetch.client.types.d.ts +15 -15
  14. package/dist/client/fetch.client.utils.d.ts +5 -2
  15. package/dist/client/index.d.ts +1 -0
  16. package/dist/command/command.d.ts +5 -5
  17. package/dist/command/command.types.d.ts +25 -25
  18. package/dist/command/command.utils.d.ts +4 -4
  19. package/dist/dispatcher/dispatcher.d.ts +3 -3
  20. package/dist/dispatcher/dispatcher.events.d.ts +2 -2
  21. package/dist/dispatcher/dispatcher.types.d.ts +7 -7
  22. package/dist/dispatcher/dispatcher.utils.d.ts +3 -3
  23. package/dist/effect/fetch.effect.d.ts +4 -4
  24. package/dist/effect/fetch.effect.types.d.ts +7 -7
  25. package/dist/index.cjs.js +1 -1
  26. package/dist/index.cjs.js.map +4 -4
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.esm.js +1 -1
  29. package/dist/index.esm.js.map +4 -4
  30. package/dist/managers/app/app.manager.constants.d.ts +2 -2
  31. package/dist/managers/app/app.manager.d.ts +3 -4
  32. package/dist/managers/app/app.manager.types.d.ts +3 -4
  33. package/dist/managers/command/command.manager.d.ts +21 -21
  34. package/dist/managers/command/command.manager.events.d.ts +3 -3
  35. package/dist/managers/command/command.manager.types.d.ts +5 -5
  36. package/dist/managers/logger/logger.manager.d.ts +3 -3
  37. package/dist/managers/logger/logger.manager.types.d.ts +12 -12
  38. package/dist/managers/logger/logger.manager.utils.d.ts +1 -1
  39. package/dist/types/fetch.types.d.ts +16 -16
  40. package/dist/types/helpers.types.d.ts +5 -5
  41. package/dist/types/http.types.d.ts +1 -1
  42. package/package.json +5 -5
  43. package/src/builder/builder.ts +48 -50
  44. package/src/builder/builder.types.ts +1 -5
  45. package/src/cache/cache.ts +24 -17
  46. package/src/cache/cache.types.ts +1 -1
  47. package/src/client/fetch.client.bindings.ts +5 -5
  48. package/src/client/fetch.client.browser.ts +89 -0
  49. package/src/client/fetch.client.server.ts +105 -0
  50. package/src/client/fetch.client.ts +5 -94
  51. package/src/client/fetch.client.utils.ts +31 -0
  52. package/src/client/index.ts +1 -0
  53. package/src/command/command.ts +6 -4
  54. package/src/command/command.types.ts +2 -2
  55. package/src/index.ts +1 -0
  56. package/src/managers/app/app.manager.ts +7 -5
  57. package/src/managers/app/app.manager.types.ts +2 -4
  58. package/src/managers/logger/logger.manager.ts +1 -1
@@ -0,0 +1,89 @@
1
+ import { getClientBindings, defaultTimeout, ClientResponseType, ClientType } from "client";
2
+ import { parseErrorResponse, parseResponse } from "./fetch.client.utils";
3
+
4
+ export const browserClient: ClientType = async (command, requestId) => {
5
+ const {
6
+ fullUrl,
7
+ headers,
8
+ payload,
9
+ config,
10
+ createAbortListener,
11
+ onBeforeRequest,
12
+ onRequestStart,
13
+ onRequestProgress,
14
+ onRequestEnd,
15
+ onResponseStart,
16
+ onResponseProgress,
17
+ onSuccess,
18
+ onError,
19
+ onResponseEnd,
20
+ onTimeoutError,
21
+ } = await getClientBindings(command, requestId);
22
+
23
+ const { method } = command;
24
+
25
+ const xhr = new XMLHttpRequest();
26
+ xhr.timeout = defaultTimeout;
27
+
28
+ const abort = () => xhr.abort();
29
+
30
+ return new Promise<ClientResponseType<unknown, unknown>>((resolve) => {
31
+ // Inject xhr options
32
+ Object.entries(config).forEach(([name, value]) => {
33
+ xhr[name] = value;
34
+ });
35
+
36
+ // Open connection
37
+ xhr.open(method, fullUrl, true);
38
+
39
+ // Set Headers
40
+ Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));
41
+
42
+ // Listen to abort signal
43
+ const unmountListener = createAbortListener(abort, resolve);
44
+
45
+ // Request handlers
46
+ xhr.upload.onprogress = onRequestProgress;
47
+
48
+ // Response handlers
49
+ xhr.onloadstart = (): void => {
50
+ onRequestEnd();
51
+ onResponseStart();
52
+ };
53
+
54
+ xhr.onprogress = onResponseProgress;
55
+
56
+ xhr.onloadend = () => {
57
+ onResponseEnd();
58
+ unmountListener();
59
+ };
60
+
61
+ xhr.ontimeout = () => onTimeoutError;
62
+
63
+ // Data handler
64
+ xhr.onreadystatechange = (e: Event) => {
65
+ const event = e as unknown as ProgressEvent<XMLHttpRequest>;
66
+ const finishedState = 4;
67
+
68
+ if (event.target && event.target.readyState === finishedState) {
69
+ const { status } = event.target;
70
+ const isSuccess = String(status).startsWith("2") || String(status).startsWith("3");
71
+
72
+ if (isSuccess) {
73
+ const data = parseResponse(event.target.response);
74
+ onSuccess(data, status, resolve);
75
+ } else {
76
+ // delay to finish after onabort/ontimeout
77
+ const data = parseErrorResponse(event.target.response);
78
+ onError(data, status, resolve);
79
+ }
80
+ }
81
+ };
82
+
83
+ // Start request
84
+ onBeforeRequest();
85
+ onRequestStart();
86
+
87
+ xhr.send(payload);
88
+ });
89
+ };
@@ -0,0 +1,105 @@
1
+ import http from "http";
2
+ import stream from "stream";
3
+
4
+ import { getClientBindings, defaultTimeout, ClientResponseType, ClientType, ClientDefaultOptionsType } from "client";
5
+ import { parseErrorResponse, parseResponse, getUploadSize, getStreamPayload } from "./fetch.client.utils";
6
+
7
+ export const serverClient: ClientType = async (command, requestId) => {
8
+ const {
9
+ fullUrl,
10
+ headers,
11
+ payload,
12
+ config,
13
+ createAbortListener,
14
+ onBeforeRequest,
15
+ onRequestStart,
16
+ onRequestProgress,
17
+ onRequestEnd,
18
+ onResponseStart,
19
+ onResponseProgress,
20
+ onSuccess,
21
+ onTimeoutError,
22
+ onError,
23
+ onResponseEnd,
24
+ } = await getClientBindings<ClientDefaultOptionsType>(command, requestId);
25
+
26
+ const { method } = command;
27
+
28
+ return new Promise<ClientResponseType<unknown, unknown>>((resolve) => {
29
+ const execute = async () => {
30
+ const options: http.RequestOptions = {
31
+ path: fullUrl,
32
+ method,
33
+ headers: headers as http.RequestOptions["headers"],
34
+ timeout: defaultTimeout,
35
+ };
36
+
37
+ // Inject xhr options
38
+ Object.entries(config).forEach(([name, value]) => {
39
+ options[name] = value;
40
+ });
41
+
42
+ let unmountListener = () => null;
43
+ onBeforeRequest();
44
+
45
+ const totalUploadBytes = payload ? Number(getUploadSize(payload)) : 0;
46
+ let uploadedBytes = 0;
47
+
48
+ const payloadChunks = await getStreamPayload(payload);
49
+
50
+ const request = http.request(options, (response) => {
51
+ response.setEncoding("utf8");
52
+
53
+ let chunks = "";
54
+ const totalDownloadBytes = Number(response.headers["content-length"]);
55
+ let downloadedBytes = 0;
56
+
57
+ response.on("data", (chunk) => {
58
+ if (!chunks) onResponseStart();
59
+ downloadedBytes += chunk.length;
60
+ chunks += chunk;
61
+ onResponseProgress({ total: totalDownloadBytes, loaded: downloadedBytes });
62
+ });
63
+
64
+ response.on("end", () => {
65
+ const { statusCode } = response;
66
+ const isSuccess = String(statusCode).startsWith("2") || String(statusCode).startsWith("3");
67
+
68
+ if (isSuccess) {
69
+ const data = parseResponse(chunks);
70
+ onSuccess(data, statusCode, resolve);
71
+ } else {
72
+ // delay to finish after onabort/ontimeout
73
+ const data = parseErrorResponse(chunks);
74
+ onError(data, statusCode, resolve);
75
+ }
76
+
77
+ unmountListener();
78
+ onResponseEnd();
79
+ });
80
+ });
81
+
82
+ unmountListener = createAbortListener(request.destroy, resolve);
83
+
84
+ request.on("timeout", () => onTimeoutError(resolve));
85
+ request.on("error", (error) => onError(error, 0, resolve));
86
+
87
+ if (payloadChunks) {
88
+ const readableStream = stream.Readable.from(payloadChunks, { objectMode: false })
89
+ .on("data", (chunk) => {
90
+ if (!uploadedBytes) onRequestStart();
91
+ uploadedBytes += chunk.length;
92
+ onRequestProgress({ total: totalUploadBytes, loaded: uploadedBytes });
93
+ })
94
+ .on("end", () => {
95
+ onRequestEnd();
96
+ });
97
+
98
+ readableStream.pipe(request);
99
+ } else {
100
+ request.end();
101
+ }
102
+ };
103
+ execute();
104
+ });
105
+ };
@@ -1,98 +1,9 @@
1
- import { getClientBindings, defaultTimeout, ClientResponseType, ClientType } from "client";
2
- import { parseErrorResponse, parseResponse } from "./fetch.client.utils";
1
+ import { browserClient, ClientType } from "client";
2
+ import { serverClient } from "./fetch.client.server";
3
3
 
4
4
  export const fetchClient: ClientType = async (command, requestId) => {
5
- if (!window.XMLHttpRequest) {
6
- throw new Error("There is no XMLHttpRequest, make sure it's provided to use Hyper Fetch built-in client.");
5
+ if (command.builder.appManager.isNodeJs || !window?.XMLHttpRequest) {
6
+ return serverClient(command, requestId);
7
7
  }
8
-
9
- const {
10
- fullUrl,
11
- headers,
12
- payload,
13
- config,
14
- createAbortListener,
15
- onBeforeRequest,
16
- onRequestStart,
17
- onRequestProgress,
18
- onRequestEnd,
19
- onResponseStart,
20
- onResponseProgress,
21
- onSuccess,
22
- // onAbortError,
23
- // onTimeoutError,
24
- onError,
25
- onResponseEnd,
26
- } = await getClientBindings(command, requestId);
27
-
28
- const { method } = command;
29
-
30
- const xhr = new XMLHttpRequest();
31
- xhr.timeout = defaultTimeout;
32
-
33
- const abort = () => xhr.abort();
34
-
35
- return new Promise<ClientResponseType<unknown, unknown>>((resolve) => {
36
- // Inject xhr options
37
- Object.entries(config).forEach(([name, value]) => {
38
- xhr[name] = value;
39
- });
40
-
41
- // Open connection
42
- xhr.open(method, fullUrl, true);
43
-
44
- // Set Headers
45
- Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));
46
-
47
- // Listen to abort signal
48
- const unmountListener = createAbortListener(abort, resolve);
49
-
50
- // Request handlers
51
- xhr.upload.onprogress = onRequestProgress;
52
-
53
- // Response handlers
54
- xhr.onloadstart = (): void => {
55
- onRequestEnd();
56
- onResponseStart();
57
- };
58
-
59
- xhr.onprogress = onResponseProgress;
60
-
61
- xhr.onloadend = () => {
62
- onResponseEnd();
63
- unmountListener();
64
- };
65
-
66
- // Error listeners
67
- // xhr.onabort = () => onAbortError(resolve);
68
- // xhr.ontimeout = () => onTimeoutError(resolve);
69
- // xhr.upload.onabort = () => onAbortError(resolve);
70
- // xhr.upload.ontimeout = () => onTimeoutError(resolve);
71
-
72
- // Data handler
73
- xhr.onreadystatechange = (e: Event) => {
74
- const event = e as unknown as ProgressEvent<XMLHttpRequest>;
75
- const finishedState = 4;
76
-
77
- if (event.target && event.target.readyState === finishedState) {
78
- const { status } = event.target;
79
- const isSuccess = String(status).startsWith("2") || String(status).startsWith("3");
80
-
81
- if (isSuccess) {
82
- const data = parseResponse(event.target.response);
83
- onSuccess(data, status, resolve);
84
- } else {
85
- // delay to finish after onabort/ontimeout
86
- const data = parseErrorResponse(event.target.response);
87
- onError(data, status, resolve);
88
- }
89
- }
90
- };
91
-
92
- // Start request
93
- onBeforeRequest();
94
- onRequestStart();
95
-
96
- xhr.send(payload);
97
- });
8
+ return browserClient(command, requestId);
98
9
  };
@@ -26,3 +26,34 @@ export const parseResponse = (response: string | unknown) => {
26
26
  export const parseErrorResponse = <T extends CommandInstance>(response: unknown): ExtractError<T> => {
27
27
  return response ? parseResponse(response) : getErrorMessage();
28
28
  };
29
+
30
+ // Request
31
+
32
+ export const getUploadSize = (payload: FormData | string) => {
33
+ if (payload instanceof FormData) {
34
+ return Array.from(payload.values())
35
+ .map((value) => (typeof value === "string" ? value.length : value.size))
36
+ .reduce((a, b) => a + b, 0);
37
+ }
38
+ return payload.length;
39
+ };
40
+
41
+ export const fileToBuffer = (file: File | Blob) => {
42
+ return new Promise<Uint8Array>((resolve) => {
43
+ const reader = new FileReader();
44
+ reader.onload = () => {
45
+ resolve(new Uint8Array(reader.result as ArrayBufferLike));
46
+ };
47
+ reader.readAsArrayBuffer(file);
48
+ });
49
+ };
50
+
51
+ export const getStreamPayload = (payload: FormData | string | null) => {
52
+ if (payload instanceof FormData) {
53
+ const parts = Array.from(payload.values()).map((value) =>
54
+ typeof value === "string" ? value : fileToBuffer(value),
55
+ );
56
+ return Promise.all(parts);
57
+ }
58
+ return payload;
59
+ };
@@ -1,5 +1,6 @@
1
1
  export * from "./fetch.client";
2
2
  export * from "./fetch.client.types";
3
3
  export * from "./fetch.client.utils";
4
+ export * from "./fetch.client.browser";
4
5
  export * from "./fetch.client.bindings";
5
6
  export * from "./fetch.client.constants";
@@ -54,7 +54,7 @@ export class Command<
54
54
  cancelable: boolean;
55
55
  retry: number;
56
56
  retryTime: number;
57
- garbageCollection: boolean;
57
+ garbageCollection: number;
58
58
  cache: boolean;
59
59
  cacheTime: number;
60
60
  queued: boolean;
@@ -97,7 +97,7 @@ export class Command<
97
97
  cancelable = false,
98
98
  retry = 0,
99
99
  retryTime = 500,
100
- garbageCollection = true,
100
+ garbageCollection = DateInterval.minute * 5,
101
101
  cache = true,
102
102
  cacheTime = DateInterval.minute * 5,
103
103
  queued = false,
@@ -357,6 +357,8 @@ export class Command<
357
357
  data: (options?.data || this.data) as any,
358
358
  };
359
359
 
360
+ const mapperFn = (mapper || this.dataMapper) as typeof mapper;
361
+
360
362
  const cloned = new Command<
361
363
  ResponseType,
362
364
  RequestDataType,
@@ -369,7 +371,7 @@ export class Command<
369
371
  P,
370
372
  Q,
371
373
  NewMappedData
372
- >(this.builder, this.commandOptions, commandDump, mapper);
374
+ >(this.builder, this.commandOptions, commandDump, mapperFn);
373
375
 
374
376
  return cloned;
375
377
  }
@@ -496,7 +498,7 @@ export class Command<
496
498
  // */
497
499
 
498
500
  // const builder = new Builder({
499
- // baseUrl: "http://localhost:3000",
501
+ // url: "http://localhost:3000",
500
502
  // });
501
503
 
502
504
  // const getUsers = builder.createCommand<{ id: string }[]>()({
@@ -45,7 +45,7 @@ export type CommandDump<
45
45
  cancelable: boolean;
46
46
  retry: number;
47
47
  retryTime: number;
48
- garbageCollection: boolean;
48
+ garbageCollection: number;
49
49
  cache: boolean;
50
50
  cacheTime: number;
51
51
  queued: boolean;
@@ -106,7 +106,7 @@ export type CommandConfig<GenericEndpoint extends string, ClientOptions> = {
106
106
  /**
107
107
  * Should we trigger garbage collection or leave data in memory
108
108
  */
109
- garbageCollection?: boolean;
109
+ garbageCollection?: number;
110
110
  /**
111
111
  * Should we save the response to cache
112
112
  */
package/src/index.ts CHANGED
@@ -10,3 +10,4 @@ export * from "./constants/http.constants";
10
10
  export * from "./managers";
11
11
  export * from "./dispatcher";
12
12
  export * from "./types";
13
+ export * from "./utils";
@@ -1,7 +1,6 @@
1
1
  import EventEmitter from "events";
2
2
 
3
- import { BuilderInstance } from "builder";
4
- import { appManagerInitialOptions, AppManagerOptionsType, getAppManagerEvents } from "managers";
3
+ import { appManagerInitialOptions, AppManagerOptionsType, getAppManagerEvents, hasDocument } from "managers";
5
4
 
6
5
  /**
7
6
  * App manager handles main application states - focus and online. Those two values can answer questions:
@@ -16,10 +15,11 @@ export class AppManager {
16
15
  emitter = new EventEmitter();
17
16
  events = getAppManagerEvents(this.emitter);
18
17
 
18
+ isNodeJs: boolean;
19
19
  isOnline: boolean;
20
20
  isFocused: boolean;
21
21
 
22
- constructor(public builder: BuilderInstance, public options?: AppManagerOptionsType) {
22
+ constructor(public options?: AppManagerOptionsType) {
23
23
  const {
24
24
  focusEvent = appManagerInitialOptions.focusEvent,
25
25
  onlineEvent = appManagerInitialOptions.onlineEvent,
@@ -30,8 +30,10 @@ export class AppManager {
30
30
  this.setInitialFocus(initiallyFocused);
31
31
  this.setInitialOnline(initiallyOnline);
32
32
 
33
- focusEvent(this.setFocused, builder);
34
- onlineEvent(this.setOnline, builder);
33
+ focusEvent(this.setFocused);
34
+ onlineEvent(this.setOnline);
35
+
36
+ this.isNodeJs = !hasDocument();
35
37
  }
36
38
 
37
39
  private setInitialFocus = async (initValue: Exclude<AppManagerOptionsType["initiallyFocused"], undefined>) => {
@@ -1,8 +1,6 @@
1
- import { BuilderInstance } from "builder";
2
-
3
1
  export type AppManagerOptionsType = {
4
2
  initiallyFocused?: boolean | (() => boolean | Promise<boolean>);
5
3
  initiallyOnline?: boolean | (() => boolean | Promise<boolean>);
6
- focusEvent?: (setFocused: (isFocused: boolean) => void, builder: BuilderInstance) => void;
7
- onlineEvent?: (setOnline: (isOnline: boolean) => void, builder: BuilderInstance) => void;
4
+ focusEvent?: (setFocused: (isFocused: boolean) => void) => void;
5
+ onlineEvent?: (setOnline: (isOnline: boolean) => void) => void;
8
6
  };
@@ -14,7 +14,7 @@ export class LoggerManager {
14
14
 
15
15
  public emitter = new EventEmitter();
16
16
 
17
- constructor(private builder: BuilderInstance, private options?: LoggerOptionsType) {
17
+ constructor(private builder: Pick<BuilderInstance, "debug">, private options?: LoggerOptionsType) {
18
18
  this.logger = this.options?.logger || logger;
19
19
  this.severity = this.options?.severity || 2;
20
20
  }