Skip to content

Commit

Permalink
readme
Browse files Browse the repository at this point in the history
  • Loading branch information
vojvodicn23 committed Sep 15, 2024
1 parent 87dc1d2 commit 8986947
Show file tree
Hide file tree
Showing 6 changed files with 208 additions and 19 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
83 changes: 82 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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<any[]>(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<T> that handles the request, error, retry.
83 changes: 82 additions & 1 deletion projects/angular-http-handler/README.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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<any[]>(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<T> that handles the request, error, retry.
16 changes: 14 additions & 2 deletions projects/angular-http-handler/package.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
10 changes: 1 addition & 9 deletions projects/angular-http-handler/src/lib/http-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ export function handle<T>(
errorHandler?: (error: HttpErrorResponse) => void,
retryCount: number = 0,
retryDelay?: number,
fallbackValue?: T | (() => T),
): (source$: Observable<T>) => Observable<T> {
return (source$: Observable<T>) =>
source$.pipe(
Expand All @@ -29,14 +28,7 @@ export function handle<T>(
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);
Expand Down
14 changes: 8 additions & 6 deletions projects/http-handler-example/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any[]>(this.apiUrl).pipe(
Expand All @@ -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();

}
}

0 comments on commit 8986947

Please sign in to comment.