File

packages/core/src/lib/services/queue/api-queue.service.ts

Description

Service class for managing and processing a queue of API requests.

This service provides functionality to add, remove, process, and manage HTTP requests stored in a queue. It enables sequential or bulk processing of requests, ensuring controlled execution and handling of API calls. The service methods offer features like processing individual items, processing all items in the queue either sequentially or all at once, and removing items from the queue. Each method is designed to handle specific aspects of queue management and processing, with attention to details like order of execution and error handling.

Usage of this service is ideal in scenarios where API requests need to be managed in a queue structure, allowing for controlled execution and monitoring of these requests.

Example :
// Adding a new item to the queue
apiQueueService.addQueueItem({ id: 'item124', method: 'POST', uri: '/api/data', payload: {...} });

// Processing a single item from the queue apiQueueService.processQueueItem('item123').subscribe(result => { console.log('Processed item 123 with result:', result); });

// Processing all items in the queue in sequential order apiQueueService.processAllQueueItemsSequential(false).subscribe(results => { console.log('Processed all items in descending order of their timestamp:', results); });

// Removing an item from the queue apiQueueService.removeQueueItem('item123');

// Processing all items in the queue and continuing on error apiQueueService.processAllQueueItems(true).subscribe(results => { console.log('Processed all items in the queue with continuation on errors:', results); });

Index

Methods

Constructor

constructor()

Methods

addQueueItem
addQueueItem(id: string, item: ApiQueueItem)

Adds an item to the queue by dispatching an action to the store. This function is specifically designed to enqueue API call requests represented by ApiQueueItem objects. Each item is identified by a unique id, which is used to manage the queue.

Example :
                 If an item with the same ID already exists, the new item will overwrite the existing one.
                 WARNING: Duplicate IDs will lead to overwriting of queue items.

                         The `method` property of the item must be one of the allowed methods ('post', 'put', 'get').
                         If an unsupported method is provided, the function will throw an error.

            The error message is: `[ApiQueue] method "${item.method}" is not allowed`.
Example :
// Example of adding an item to the API queue
addQueueItem('12345', { method: 'post', url: '/api/data', payload: {...} });
Parameters :
Name Type Optional Description
id string No
  • The unique identifier for the queue item. It's crucial to ensure that this ID is unique within the queue. If an item with the same ID already exists, the new item will overwrite the existing one. WARNING: Duplicate IDs will lead to overwriting of queue items.
item ApiQueueItem No
  • The item to be enqueued. This should be an object of type ApiQueueItem. The method property of the item must be one of the allowed methods ('post', 'put', 'get'). If an unsupported method is provided, the function will throw an error.
Returns : void

This function does not return a value. It adds the item to the queue via a dispatch action.

getQueue
getQueue()

Retrieves the current state of the API queue and converts it into an array of Observables.

This method subscribes to the store to access the API queue. It then maps the queue object, which is an associative array, into a linear array of ApiQueueItem instances. If the queue is empty, a warning is logged. This method is useful for tracking the state and contents of the API queue at a given moment.

Note: This method takes a snapshot of the queue at the time of subscription. It does not provide a continuous stream of queue updates. To get real-time updates, consider subscribing directly to the store's observable.

The array represents all items currently in the queue. If the queue is empty, it emits an empty array.

Example :
// Example usage
this.getQueue().subscribe(queueItems => {
  console.log('Current queue items:', queueItems);
});
Returns : Observable<ApiQueueItem[]>

An Observable that emits an array of ApiQueueItem. The array represents all items currently in the queue. If the queue is empty, it emits an empty array.

getQueueItem
getQueueItem(id: string)

Retrieves a specific item from the API queue by its ID.

This method subscribes to the store and selects a single item from the API queue based on the provided ID. It employs a pipeline to fetch the item: the getApiQueueItem selector is used to retrieve the item, and a map operator processes the result. If the item with the specified ID does not exist in the queue, a warning is logged, and null is returned.

This method is ideal for accessing a specific queue item when its ID is known, allowing for targeted operations or checks on that particular item.

If no item with the given ID exists in the queue, the Observable emits null.

Example :
// Example usage
this.getQueueItem('item123').subscribe(item => {
  if (item) {
    console.log('Found item:', item);
  } else {
    console.log('Item not found in the queue');
  }
});
Parameters :
Name Type Optional Description
id string No
  • The unique identifier of the item within the queue.
Returns : Observable<ApiQueueItem>

An Observable emitting the requested ApiQueueItem. If no item with the given ID exists in the queue, the Observable emits null.

processAllQueueItems
processAllQueueItems(continueOnError: unknown)
Type parameters :
  • T

Processes all items in the API queue and collects their responses.

Iterates over each item in the queue and processes them using buildHttpRequest. If a request fails, the method can either continue processing the remaining items or stop, based on the continueOnError parameter. It returns an Observable that emits an array containing the responses or errors from all the processed items.

The function currently returns Observable<any[]> indicating an array of any type. Future improvements should aim to specify a more accurate return type or utilize generics for increased type safety.

Example :
                                      after a request failure. Defaults to `true`.
                         queue items.
Example :
this.processAllQueueItems().subscribe(results => {
  // Handle the array of responses or errors
});
Parameters :
Name Type Optional Default value Description
continueOnError unknown No true
  • Determines whether to continue with the next item in the queue after a request failure. Defaults to true.
Returns : Observable<T[]>

An Observable emitting an array of either responses or errors from the processed queue items.

processAllQueueItemsSequential
processAllQueueItemsSequential(ascending: unknown)
Type parameters :
  • T

Processes all items in the queue sequentially, based on their timestamp ordering.

This method first orders the items in the API queue by their timestamp, either in ascending or descending order as specified by the ascending parameter. It then processes each item using buildHttpRequest, ensuring that each request is completed before the next begins. This sequential processing is crucial when the order of execution matters for HTTP requests in the queue. The method returns an Observable that emits the responses following the same order as the queue items were processed.

The function currently returns Observable<any>, indicating a broad type. Future improvements should focus on specifying a more accurate return type or utilizing generics for increased type safety.

Example :
                                timestamp. Defaults to `true`.
Example :
this.processAllQueueItemsSequential().subscribe(response => {
  // Handle each response in the order of queue processing
});
Parameters :
Name Type Optional Default value Description
ascending unknown No true
  • Determines whether the queue items are processed in ascending order of their timestamp. Defaults to true.
Returns : Observable<T>

An Observable emitting the responses of the HTTP requests in the order they were processed.

processQueueItem
processQueueItem(id: string)
Type parameters :
  • T

Processes an item from the API queue identified by its ID.

Retrieves the specified item from the queue and applies processing logic as defined in buildHttpRequest. If the item is not found, logs a warning and returns an Observable emitting null.

If the item does not exist, the Observable emits null.

Example :
// Example usage
this.processQueueItem('item123').subscribe(result => {
  if (result) {
    console.log('Processing result:', result);
  } else {
    console.log('Item not found in the queue');
  }
});
Parameters :
Name Type Optional Description
id string No
  • The unique identifier of the item within the queue to be processed.
Returns : Observable<T>

An Observable that emits the result of processing the queue item. If the item does not exist, the Observable emits null.

removeAllQueueItem
removeAllQueueItem()

Clears all items from the API queue.

This method dispatches an action to empty the entire API queue, effectively removing all items that are currently queued. It is useful for scenarios where a complete reset of the queue is required, such as during initialization or after processing a batch of items. The function does not return any value, as its primary purpose is to trigger a state change in the store.

Note: Use this method with caution as it will irreversibly clear all items in the queue. Ensure that this action does not disrupt any ongoing processes that rely on the queue's contents.

Example :
// Example usage
this.removeAllQueueItem();
// This will dispatch an action to empty the entire API queue.
Returns : void
removeQueueItem
removeQueueItem(id: string)

Removes a specific item from the API queue using its ID.

This method dispatches an action to remove an item from the queue, identified by the provided ID. It is essential for managing the queue by eliminating items that are no longer needed or have been processed. The function does not return any value, as it primarily triggers an action within the store.

Note: This method assumes the existence of the item in the queue. It does not perform a check to confirm the presence of the item before attempting to remove it. Therefore, it's recommended to verify the item's existence in the queue if uncertainty exists.

Example :
// Example usage
this.removeQueueItem('item123');
// The item with ID 'item123' will be dispatched for removal from the queue.
Parameters :
Name Type Optional Description
id string No
  • The unique identifier of the item to be removed from the queue.
Returns : void

results matching ""

    No results matching ""