diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5bd9828 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Nikola Vojvodic + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 7321bd0..e051918 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # Angular HTTP Handler +## Introduction + An Angular library for handling HTTP requests with loading state management, error handling, retry logic, and fallback values. +Supported Angular versions: 15, 16, 17, 18. ## Features @@ -15,4 +18,82 @@ An Angular library for handling HTTP requests with loading state management, err To install the library, run the following command: ```bash -npm install angular'http-handler +npm install angular-http-handler +``` + +## Usage + +In your Angular component, you can apply the handle function to any HTTP request. +Here's an example using HttpClient: +```typescript +import { HttpClient } from '@angular/common/http'; +import { Component, inject, OnInit } from '@angular/core'; +import { handle } from 'angular-http-handler'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'] +}) +export class AppComponent implements OnInit { + private apiUrl = 'YOUR API URL'; + http = inject(HttpClient); + + loading = false; + response: any[] = []; + + ngOnInit(): void { + this.http.get(this.apiUrl).pipe( + handle( + (loading) => { + this.loading = loading; + console.log(loading); + }, + (response) => { + this.response = response; + console.log(response); + }, + (error) => { // OPTIONAL - custom error handler + console.log(error); + }, + 2, // OPTIONAL - retry count + 1000, // OTIONAL - retry delay + ) + ).subscribe(); + } +} +``` + +## Fallback Response Behavior + +The `handle` function guarantees that a fallback response will always be returned in case of an error, based on the type of the response (`T`). + +- **If the expected response is an array type (e.g., `string[]`, `any[]`)**, the fallback will be an empty array (`[]`). +- **If the expected response is any other type (e.g., `string`, `number`, `object`)**, the fallback will be `null`. + +This ensures that the `dataSetter` will always receive a value of type `T` even in the case of an error, simplifying error handling and avoiding undefined values in your application. + + +## API + +The handle function manages HTTP requests with loading state, error handling and retry. + +Parameters: + +- loadingSetter: (loading: boolean) => void +Function to set the loading state (e.g., this.loading = loading). + +- dataSetter: (response: T) => void +Function to set the data when the request succeeds (e.g., this.data = response). + +- errorHandler?: (error: HttpErrorResponse) => void +Optional function to handle errors (e.g., console.error(error)). + +- retryCount?: number +Number of retries for failed requests. Defaults to 0. + +- retryDelay?: number +Delay between retries in milliseconds. + +- Returns +An Observable that handles the request, error, retry. \ No newline at end of file diff --git a/projects/angular-http-handler/README.md b/projects/angular-http-handler/README.md index 7321bd0..e051918 100644 --- a/projects/angular-http-handler/README.md +++ b/projects/angular-http-handler/README.md @@ -1,6 +1,9 @@ # Angular HTTP Handler +## Introduction + An Angular library for handling HTTP requests with loading state management, error handling, retry logic, and fallback values. +Supported Angular versions: 15, 16, 17, 18. ## Features @@ -15,4 +18,82 @@ An Angular library for handling HTTP requests with loading state management, err To install the library, run the following command: ```bash -npm install angular'http-handler +npm install angular-http-handler +``` + +## Usage + +In your Angular component, you can apply the handle function to any HTTP request. +Here's an example using HttpClient: +```typescript +import { HttpClient } from '@angular/common/http'; +import { Component, inject, OnInit } from '@angular/core'; +import { handle } from 'angular-http-handler'; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.css'] +}) +export class AppComponent implements OnInit { + private apiUrl = 'YOUR API URL'; + http = inject(HttpClient); + + loading = false; + response: any[] = []; + + ngOnInit(): void { + this.http.get(this.apiUrl).pipe( + handle( + (loading) => { + this.loading = loading; + console.log(loading); + }, + (response) => { + this.response = response; + console.log(response); + }, + (error) => { // OPTIONAL - custom error handler + console.log(error); + }, + 2, // OPTIONAL - retry count + 1000, // OTIONAL - retry delay + ) + ).subscribe(); + } +} +``` + +## Fallback Response Behavior + +The `handle` function guarantees that a fallback response will always be returned in case of an error, based on the type of the response (`T`). + +- **If the expected response is an array type (e.g., `string[]`, `any[]`)**, the fallback will be an empty array (`[]`). +- **If the expected response is any other type (e.g., `string`, `number`, `object`)**, the fallback will be `null`. + +This ensures that the `dataSetter` will always receive a value of type `T` even in the case of an error, simplifying error handling and avoiding undefined values in your application. + + +## API + +The handle function manages HTTP requests with loading state, error handling and retry. + +Parameters: + +- loadingSetter: (loading: boolean) => void +Function to set the loading state (e.g., this.loading = loading). + +- dataSetter: (response: T) => void +Function to set the data when the request succeeds (e.g., this.data = response). + +- errorHandler?: (error: HttpErrorResponse) => void +Optional function to handle errors (e.g., console.error(error)). + +- retryCount?: number +Number of retries for failed requests. Defaults to 0. + +- retryDelay?: number +Delay between retries in milliseconds. + +- Returns +An Observable that handles the request, error, retry. \ No newline at end of file diff --git a/projects/angular-http-handler/package.json b/projects/angular-http-handler/package.json index 1cfcaa4..645e8ff 100644 --- a/projects/angular-http-handler/package.json +++ b/projects/angular-http-handler/package.json @@ -1,9 +1,21 @@ { "name": "angular-http-handler", "version": "0.0.1", + "description": "This is the http handler utility for Angular http requests", + "keywords": ["http", "angular", "loading", "error-handler"], + "author": { + "name": "Nikola Vojvodic", + "url": "https://github.com/vojvodicn23" + }, + "homepage": "https://github.com/vojvodicn23", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/vojvodicn23/http-handler" + }, "peerDependencies": { - "@angular/common": "^16.2.0", - "@angular/core": "^16.2.0" + "@angular/common": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0", + "@angular/core": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0" }, "dependencies": { "tslib": "^2.3.0" diff --git a/projects/angular-http-handler/src/lib/http-handler.ts b/projects/angular-http-handler/src/lib/http-handler.ts index feb223a..38fd9f8 100644 --- a/projects/angular-http-handler/src/lib/http-handler.ts +++ b/projects/angular-http-handler/src/lib/http-handler.ts @@ -7,7 +7,6 @@ export function handle( errorHandler?: (error: HttpErrorResponse) => void, retryCount: number = 0, retryDelay?: number, - fallbackValue?: T | (() => T), ): (source$: Observable) => Observable { return (source$: Observable) => source$.pipe( @@ -29,14 +28,7 @@ export function handle( errorHandler(error); } - let fallback: T; - if (typeof fallbackValue === 'function') { - fallback = (fallbackValue as () => T)(); - } else if (fallbackValue !== undefined) { - fallback = fallbackValue; - } else { - fallback = (Array.isArray([] as unknown as T) ? [] : null) as T; - } + const fallback = (Array.isArray([] as unknown as T) ? [] : null) as T; dataSetter(fallback); return of(fallback); diff --git a/projects/http-handler-example/src/app/app.component.ts b/projects/http-handler-example/src/app/app.component.ts index 8d5a386..8a5a14c 100644 --- a/projects/http-handler-example/src/app/app.component.ts +++ b/projects/http-handler-example/src/app/app.component.ts @@ -8,11 +8,11 @@ import { handle } from 'angular-http-handler'; styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { - - private apiUrl = 'https://jsonplaceholder.typicode.com/posts'; + private apiUrl = 'YOUR API URL'; http = inject(HttpClient); loading = false; + response: any[] = []; ngOnInit(): void { this.http.get(this.apiUrl).pipe( @@ -21,12 +21,14 @@ export class AppComponent implements OnInit { this.loading = loading; console.log(loading) }, - (reports) => { - console.log(reports) + (response) => { + this.response = response; + console.log(response) }, - (e) => console.log(e, 'custom'), + (e) => console.log(e, 'custom'), // OPTIONAL - custom error handler + 2, // OPTIONAL - retry count + 1000, // OTIONAL - retry delay ) ).subscribe(); - } }