http-core-service
v1.2.2
Published
This Angular Module is the best HTTP request service for API requests for both rest and query endpoint services.
Downloads
11
Maintainers
Readme
HTTP Service
This Angular Module allows you to have a global HTTP service. Provided are interceptors for http error handling, JWT token injection with API calls and secureCookie handle with credentails. For the hTTP Requests, a retry and next time request are added and configurable. There is also an interceptor to handle unauthorized 401, 403 errors and redirects the user to the defined setting.
There is also a delay when a request is made before isPending$ is true - this is great for spinners that appear only when a request is taking longer then 3 seconds (soon configurable)
Installation
npm install http-core-service
Scaffolding
Import the module into your project under imports
imports: [
BrowserModule,
AppRoutingModule,
HttpCoreServiceModule,
],
Use
Define the paramiters for the settings for the HTTP Request service like the following.
imports: [
BrowserModule,
AppRoutingModule,
HttpCoreServiceModule.forRoot({
sessionTokenName:'token',
delayNextRequestBy: 1.5,
requestRetries: 3,
redirect_unauthothized: 'default',
includeCookies: true
}),
],
HTTP Request settings
| SETTING | TYPE | Defaut | Description | | ----- | ---- | ------ | ----------- | | sessionTokenName | STRING | 'token' | grabs token from session for JWT Bearer token | | delayNextRequestBy | NUMBER | 1.5 secs | if request fails, delay next request by #secs | | requestRetries | NUMBER | 3 |number of retries before alerts user of error | | includeCookies | STRING | BOOLEAN | adds credentails:true to headers for cookies |
Usage and Syntax
Extend a Class with generic type - or <any[]>
export class OnboardingMerchantService extends HttpCore<any>
Call Super to initialize the extended class and provide the end point service path as array
Inport the HTTPClient
module in the contructor as _http
and pass in and the REST path in super()
to create an instance of the service.
super(_http, baseUrl, ['onboarding', 'details', { size: 12 }])
BaseURL: is the API base URL - avoid adding paths to the base URL to allow more flexability
Paths: string[] - this provides a way to dynamically modify your paths. You may include just one path for the API such as ['onboarding/details]
or manage paths indipendantly for easy reading.
Query type - if you have a query style param that needs to be added to the path, define it as an object { size: 12 }
and the request will convert to ?size=12
. Encoding will also be provided. You may add multiple objects or just one object for the query.
Then call the http method - this.getAllRecords()
Extended Class includes the following Observables
data$ = new BehaviorSubject<T[]>(null)
isLoading$ = new BehaviorSubject<boolean>(false) // deprecated
isSaving$ = new BehaviorSubject<boolean>(false) // deprecated
isPending$ = new BehaviorSubject<boolean>(false) // replaaces both isLoading$ and isSaving$
error$ = new BehaviorSubject<HttpError>(null)
The following are the moethods avilable for HTTP request
| SETTING | TYPE | Defaut | Description | | ----- | ---- | ------ | ----------- | | sessionTokenName | STRING | 'token' | grabs token from session for JWT Bearer token | | delayNextRequestBy | NUMBER | 1.5 secs | if request fails, delay next request by #secs | | requestRetries | NUMBER | 3 |number of retries before alerts user of error | | includeCookies | STRING | BOOLEAN | adds credentails:true to headers for cookies |
The better method is to create a service that you extend and call the method from it.
To use the data$ from that servive, define an Observable in the component Observable<any[]>
Then in your component Oninit bind the data this.data$ = this.service.data$
Now its available to the component.
export class myDataService extends HttpCore<any> {
myData$ = new Observable<any[]>()
constructor(protected _http: HttpClient) {
super(_http, baseUrl, ['onboarding','details'])
}
getOnboardingData() {
this.getAllRecords()
}
}
Then in the component you do the following
constructor(private dataService: myDataService) {}
onInit() {
this.dataService.getOnboardingData()
this.myData$ = this.dataService.data$
}
now you can do the following in your view
<div *ngif="(myData$ | async) as data">
{{ data.title }}
<img [src]="data.urlImage">
</div>
Utils - Helpers
The following utils are included for model creation and validation and other
export { IDUtils } from './utils/id-utils'
export { DateUtils } from './utils/date-utils'
export { JSONValidation } from './utils/json-validation'
IDUtils
- id - generates a random id (numeric)
- today - generates date (epoch - milliseconds)
- randomNumber - random int
- randomString - random string
- RandomAlphaNumeric - random alphnumeric
- RandomFormat - provide a mask (000-AAA-000AA) and generates alpha number in format
DateUtils
- currentDateTime - current time (hour, min)
- currentDay - current day ()
- dateToEpoch - converts date object to epoch
- epochToDate - converts epoch to date object
- today - date object for today
- epochDay - epoch of today
- calculateAge - age in epoch
JSONValidation
- isJSON - exhastive check if object is a valid json object
- strict - simple check if object if json
- isString - true/false if is a string
- isObject - true/false if is a object