api-core-lib 11.0.0 → 11.2.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.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method } from 'axios';
2
+ import { Dispatch, SetStateAction } from 'react';
2
3
 
3
4
  /**
4
5
  * @file src/types.ts
@@ -449,11 +450,134 @@ declare const processResponse: <T>(responseOrError: AxiosResponse<any> | ApiErro
449
450
  declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): UseApiReturn<T>;
450
451
 
451
452
  /**
452
- * A production-ready custom hook that dynamically builds a set of executable and fully-typed API actions.
453
- * It provides a unified, ergonomic API for each action, collocating state and execution logic,
454
- * while guaranteeing stable function references to prevent re-renders.
453
+ * هوك متقدم يقوم ببناء مجموعة من الإجراءات القابلة للتنفيذ من إعدادات موديول API،
454
+ * مع فصل تام بين الدوال المستقرة والحالات المتغيرة لمنع الحلقات اللانهائية.
455
455
  */
456
- declare function useApiModule<TModule extends ApiModuleConfig>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions): ModuleActions<TModule>;
456
+ declare function useApiModule<TModule extends ApiModuleConfig>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions): any;
457
+
458
+ /**
459
+ * Represents a standardized API error structure.
460
+ */
461
+ interface ApiErrorRecord {
462
+ /** The HTTP status code of the error response (e.g., 404, 500). */
463
+ status?: number;
464
+ /** A user-friendly error message. */
465
+ message: string;
466
+ /** A dictionary of validation errors, where the key is the field name. */
467
+ validationErrors?: Record<string, string[]>;
468
+ }
469
+ /**
470
+ * Represents the standard wrapper for all API responses processed by the client.
471
+ * @template T The data type of the successful response payload.
472
+ */
473
+ interface StandardResponseRecord<T> {
474
+ /** The data payload from the API on success, or null on failure. */
475
+ data: T | null;
476
+ /** A boolean indicating if the request was successful (e.g., status 2xx). */
477
+ success: boolean;
478
+ /** A boolean indicating if the request is currently in flight. */
479
+ loading: boolean;
480
+ /** An ApiError object if the request failed, otherwise null. */
481
+ error: ApiErrorRecord | null;
482
+ /** An optional success or error message from the API. */
483
+ message?: string;
484
+ /** Validation errors returned from the API (typically on 422 Unprocessable Entity responses). */
485
+ validationErrors?: Record<string, string[]>;
486
+ /** The raw Axios response object for advanced use cases. */
487
+ rawResponse?: AxiosResponse<T>;
488
+ }
489
+ /**
490
+ * The state object managed by the `useApiRecord` hook.
491
+ * It mirrors the StandardResponseRecord but separates the `loading` flag for more granular control.
492
+ * @template T The data type of the record.
493
+ */
494
+ interface UseApiRecordState<T> extends Omit<StandardResponseRecord<T>, 'loading'> {
495
+ /** A boolean indicating if a fetch or action is currently in progress. */
496
+ loading: boolean;
497
+ }
498
+ /**
499
+ * The set of functions provided by the hook to interact with the API record.
500
+ * @template T The data type of the record.
501
+ */
502
+ interface UseApiRecordActions<T> {
503
+ /**
504
+ * Manually re-fetches the record from the API.
505
+ * @returns A promise that resolves with the API response.
506
+ */
507
+ fetch: () => Promise<StandardResponseRecord<T>>;
508
+ /**
509
+ * Updates parts of the record using an HTTP PATCH request.
510
+ * @param updatedItem - An object containing only the fields to be updated.
511
+ * @param options - Optional Axios request configuration to merge with the default config.
512
+ * @returns A promise that resolves with the API response.
513
+ */
514
+ update: (updatedItem: Partial<T>, options?: AxiosRequestConfig) => Promise<StandardResponseRecord<T>>;
515
+ /**
516
+ * Replaces the entire record with new data using an HTTP PUT request.
517
+ * @param item - The complete new object for the record.
518
+ * @param options - Optional Axios request configuration to merge with the default config.
519
+ * @returns A promise that resolves with the API response.
520
+ */
521
+ put: (item: T, options?: AxiosRequestConfig) => Promise<StandardResponseRecord<T>>;
522
+ /**
523
+ * Deletes the record from the API using an HTTP DELETE request.
524
+ * @param options - Optional Axios request configuration to merge with the default config.
525
+ * @returns A promise that resolves with the API response (data will be null).
526
+ */
527
+ remove: (options?: AxiosRequestConfig) => Promise<StandardResponseRecord<null>>;
528
+ /** Resets the hook's state to its initial value. */
529
+ resetState: () => void;
530
+ }
531
+ /**
532
+ * The configuration object for the `useApiRecord` hook.
533
+ * @template T The data type of the record.
534
+ */
535
+ interface UseApiRecordConfig<T> {
536
+ /** The base API endpoint for the resource (without the ID). Example: '/users' */
537
+ endpoint: string;
538
+ /** The unique identifier of the record to fetch, update, or delete. */
539
+ recordId?: string | number | null;
540
+ /** Optional initial data to display before the first fetch completes. Useful for optimistic UI. */
541
+ initialData?: T | null;
542
+ /** If `true`, the hook will automatically fetch the data on mount. Defaults to `true`. */
543
+ enabled?: boolean;
544
+ /** If `true`, the record will be re-fetched after any successful mutation (update, put, remove). Defaults to `true`. */
545
+ refetchOnSuccess?: boolean;
546
+ /** Additional Axios request config to be merged with every request made by the hook. */
547
+ requestConfig?: AxiosRequestConfig;
548
+ /** A callback function that fires upon any successful API operation. */
549
+ onSuccess?: (message: string, data?: T | null) => void;
550
+ /** A callback function that fires upon any failed API operation. */
551
+ onError?: (message: string, error?: ApiErrorRecord) => void;
552
+ }
553
+ /**
554
+ * The return value of the `useApiRecord` hook.
555
+ * @template T The data type of the record.
556
+ */
557
+ interface UseApiRecordReturn<T> {
558
+ /** The current state of the API request and data. */
559
+ state: UseApiRecordState<T>;
560
+ /** A collection of functions to perform operations on the record. */
561
+ actions: UseApiRecordActions<T>;
562
+ /** A React state dispatcher to manually set the state (for advanced use cases). */
563
+ setState: Dispatch<SetStateAction<UseApiRecordState<T>>>;
564
+ }
565
+
566
+ /**
567
+ * A robust custom hook to manage the lifecycle of a single API record (fetch, update, delete).
568
+ * It handles state, loading, errors, and provides actions to interact with the API.
569
+ * This version is fortified against common issues like race conditions and infinite loops.
570
+ *
571
+ * @template T The expected type of the API record.
572
+ * @param {AxiosInstance} axiosInstance - A pre-configured Axios instance.
573
+ * @param {UseApiRecordConfig<T>} config - Configuration object for the hook.
574
+ * @returns {UseApiRecordReturn<T>} An object containing the state, setState function, and actions.
575
+ */
576
+ declare function useApiRecord<T>(axiosInstance: AxiosInstance, config: UseApiRecordConfig<T>): UseApiRecordReturn<T>;
577
+
578
+ type EffectCallback = () => (void | (() => void));
579
+ type DependencyList = readonly any[];
580
+ declare function useDeepCompareEffect(callback: EffectCallback, dependencies: DependencyList): void;
457
581
 
458
582
  type ApiResourceStatus = 'idle' | 'loading' | 'success' | 'error';
459
583
  interface UseApiResourceState<T> {
@@ -501,4 +625,4 @@ interface UseApiResourceReturn<T, TCreate, TUpdate, TPathParams> {
501
625
  setQuery: React.Dispatch<React.SetStateAction<QueryOptions>>;
502
626
  }
503
627
 
504
- export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiModuleConfig, type ApiResourceStatus, type ApiResponse, type ExecutableAction, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiQuery, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi, useApiModule };
628
+ export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiErrorRecord, type ApiModuleConfig, type ApiResourceStatus, type ApiResponse, type ExecutableAction, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type StandardResponseRecord, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiQuery, type UseApiRecordActions, type UseApiRecordConfig, type UseApiRecordReturn, type UseApiRecordState, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi, useApiModule, useApiRecord, useDeepCompareEffect };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig, AxiosProgressEvent, AxiosInstance, Method } from 'axios';
2
+ import { Dispatch, SetStateAction } from 'react';
2
3
 
3
4
  /**
4
5
  * @file src/types.ts
@@ -449,11 +450,134 @@ declare const processResponse: <T>(responseOrError: AxiosResponse<any> | ApiErro
449
450
  declare function useApi<T>(axiosInstance: AxiosInstance, config: UseApiConfig<T>): UseApiReturn<T>;
450
451
 
451
452
  /**
452
- * A production-ready custom hook that dynamically builds a set of executable and fully-typed API actions.
453
- * It provides a unified, ergonomic API for each action, collocating state and execution logic,
454
- * while guaranteeing stable function references to prevent re-renders.
453
+ * هوك متقدم يقوم ببناء مجموعة من الإجراءات القابلة للتنفيذ من إعدادات موديول API،
454
+ * مع فصل تام بين الدوال المستقرة والحالات المتغيرة لمنع الحلقات اللانهائية.
455
455
  */
456
- declare function useApiModule<TModule extends ApiModuleConfig>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions): ModuleActions<TModule>;
456
+ declare function useApiModule<TModule extends ApiModuleConfig>(axiosInstance: AxiosInstance, moduleConfig: TModule, options?: UseApiModuleOptions): any;
457
+
458
+ /**
459
+ * Represents a standardized API error structure.
460
+ */
461
+ interface ApiErrorRecord {
462
+ /** The HTTP status code of the error response (e.g., 404, 500). */
463
+ status?: number;
464
+ /** A user-friendly error message. */
465
+ message: string;
466
+ /** A dictionary of validation errors, where the key is the field name. */
467
+ validationErrors?: Record<string, string[]>;
468
+ }
469
+ /**
470
+ * Represents the standard wrapper for all API responses processed by the client.
471
+ * @template T The data type of the successful response payload.
472
+ */
473
+ interface StandardResponseRecord<T> {
474
+ /** The data payload from the API on success, or null on failure. */
475
+ data: T | null;
476
+ /** A boolean indicating if the request was successful (e.g., status 2xx). */
477
+ success: boolean;
478
+ /** A boolean indicating if the request is currently in flight. */
479
+ loading: boolean;
480
+ /** An ApiError object if the request failed, otherwise null. */
481
+ error: ApiErrorRecord | null;
482
+ /** An optional success or error message from the API. */
483
+ message?: string;
484
+ /** Validation errors returned from the API (typically on 422 Unprocessable Entity responses). */
485
+ validationErrors?: Record<string, string[]>;
486
+ /** The raw Axios response object for advanced use cases. */
487
+ rawResponse?: AxiosResponse<T>;
488
+ }
489
+ /**
490
+ * The state object managed by the `useApiRecord` hook.
491
+ * It mirrors the StandardResponseRecord but separates the `loading` flag for more granular control.
492
+ * @template T The data type of the record.
493
+ */
494
+ interface UseApiRecordState<T> extends Omit<StandardResponseRecord<T>, 'loading'> {
495
+ /** A boolean indicating if a fetch or action is currently in progress. */
496
+ loading: boolean;
497
+ }
498
+ /**
499
+ * The set of functions provided by the hook to interact with the API record.
500
+ * @template T The data type of the record.
501
+ */
502
+ interface UseApiRecordActions<T> {
503
+ /**
504
+ * Manually re-fetches the record from the API.
505
+ * @returns A promise that resolves with the API response.
506
+ */
507
+ fetch: () => Promise<StandardResponseRecord<T>>;
508
+ /**
509
+ * Updates parts of the record using an HTTP PATCH request.
510
+ * @param updatedItem - An object containing only the fields to be updated.
511
+ * @param options - Optional Axios request configuration to merge with the default config.
512
+ * @returns A promise that resolves with the API response.
513
+ */
514
+ update: (updatedItem: Partial<T>, options?: AxiosRequestConfig) => Promise<StandardResponseRecord<T>>;
515
+ /**
516
+ * Replaces the entire record with new data using an HTTP PUT request.
517
+ * @param item - The complete new object for the record.
518
+ * @param options - Optional Axios request configuration to merge with the default config.
519
+ * @returns A promise that resolves with the API response.
520
+ */
521
+ put: (item: T, options?: AxiosRequestConfig) => Promise<StandardResponseRecord<T>>;
522
+ /**
523
+ * Deletes the record from the API using an HTTP DELETE request.
524
+ * @param options - Optional Axios request configuration to merge with the default config.
525
+ * @returns A promise that resolves with the API response (data will be null).
526
+ */
527
+ remove: (options?: AxiosRequestConfig) => Promise<StandardResponseRecord<null>>;
528
+ /** Resets the hook's state to its initial value. */
529
+ resetState: () => void;
530
+ }
531
+ /**
532
+ * The configuration object for the `useApiRecord` hook.
533
+ * @template T The data type of the record.
534
+ */
535
+ interface UseApiRecordConfig<T> {
536
+ /** The base API endpoint for the resource (without the ID). Example: '/users' */
537
+ endpoint: string;
538
+ /** The unique identifier of the record to fetch, update, or delete. */
539
+ recordId?: string | number | null;
540
+ /** Optional initial data to display before the first fetch completes. Useful for optimistic UI. */
541
+ initialData?: T | null;
542
+ /** If `true`, the hook will automatically fetch the data on mount. Defaults to `true`. */
543
+ enabled?: boolean;
544
+ /** If `true`, the record will be re-fetched after any successful mutation (update, put, remove). Defaults to `true`. */
545
+ refetchOnSuccess?: boolean;
546
+ /** Additional Axios request config to be merged with every request made by the hook. */
547
+ requestConfig?: AxiosRequestConfig;
548
+ /** A callback function that fires upon any successful API operation. */
549
+ onSuccess?: (message: string, data?: T | null) => void;
550
+ /** A callback function that fires upon any failed API operation. */
551
+ onError?: (message: string, error?: ApiErrorRecord) => void;
552
+ }
553
+ /**
554
+ * The return value of the `useApiRecord` hook.
555
+ * @template T The data type of the record.
556
+ */
557
+ interface UseApiRecordReturn<T> {
558
+ /** The current state of the API request and data. */
559
+ state: UseApiRecordState<T>;
560
+ /** A collection of functions to perform operations on the record. */
561
+ actions: UseApiRecordActions<T>;
562
+ /** A React state dispatcher to manually set the state (for advanced use cases). */
563
+ setState: Dispatch<SetStateAction<UseApiRecordState<T>>>;
564
+ }
565
+
566
+ /**
567
+ * A robust custom hook to manage the lifecycle of a single API record (fetch, update, delete).
568
+ * It handles state, loading, errors, and provides actions to interact with the API.
569
+ * This version is fortified against common issues like race conditions and infinite loops.
570
+ *
571
+ * @template T The expected type of the API record.
572
+ * @param {AxiosInstance} axiosInstance - A pre-configured Axios instance.
573
+ * @param {UseApiRecordConfig<T>} config - Configuration object for the hook.
574
+ * @returns {UseApiRecordReturn<T>} An object containing the state, setState function, and actions.
575
+ */
576
+ declare function useApiRecord<T>(axiosInstance: AxiosInstance, config: UseApiRecordConfig<T>): UseApiRecordReturn<T>;
577
+
578
+ type EffectCallback = () => (void | (() => void));
579
+ type DependencyList = readonly any[];
580
+ declare function useDeepCompareEffect(callback: EffectCallback, dependencies: DependencyList): void;
457
581
 
458
582
  type ApiResourceStatus = 'idle' | 'loading' | 'success' | 'error';
459
583
  interface UseApiResourceState<T> {
@@ -501,4 +625,4 @@ interface UseApiResourceReturn<T, TCreate, TUpdate, TPathParams> {
501
625
  setQuery: React.Dispatch<React.SetStateAction<QueryOptions>>;
502
626
  }
503
627
 
504
- export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiModuleConfig, type ApiResourceStatus, type ApiResponse, type ExecutableAction, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiQuery, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi, useApiModule };
628
+ export { type ActionConfig, type ActionOptions, type ActionState, type ApiClientConfig, type ApiError, type ApiErrorRecord, type ApiModuleConfig, type ApiResourceStatus, type ApiResponse, type ExecutableAction, type LogLevel, type Middleware, type MiddlewareContext, type ModuleActions, type PaginationMeta, type QueryOptions, type RefreshTokenConfig, type RequestConfig, type StandardResponse, type StandardResponseRecord, type TokenManager, type Tokens, type UseApiActions, type UseApiConfig, type UseApiModuleOptions, type UseApiQuery, type UseApiRecordActions, type UseApiRecordConfig, type UseApiRecordReturn, type UseApiRecordState, type UseApiResourceActions, type UseApiResourceConfig, type UseApiResourceReturn, type UseApiResourceState, type UseApiReturn, type UseApiState, type ValidationError, buildPaginateQuery, cacheManager, createApiActions, createApiClient, createApiServices, processResponse, useApi, useApiModule, useApiRecord, useDeepCompareEffect };