ngx-http-annotations
Version:
This is a library to angular to use http request via decorator/annotations
217 lines (163 loc) • 7.1 kB
Markdown
# ngx-http-annotations
This library allows to interact with rest api in your angular app.
It contains:
- Annotations for http methods (, , , , , , )
- Annotations for adding headers, setting produces results and intercepting response
- Params annotations
forked from : https://github.com/Mixalloff/ngx-http-rest
### Installation
Install through npm:
```sh
$ npm install ngx-http-annotations --save
```
### Development
Example of using library.
1) Plug the HttpRestModule into your AppModule
```typescript
import { NgxHttpAnnotationsModule } from 'ngx-http-annotations';
import { NgModule } from '@angular/core';
export class AppModule {
}
```
2) Create a service to work with rest api. Put annotations on the class, methods and params.
```typescript
import { GET, POST, DELETE, Path, PathParam, Body, QueryParam, QueryParams, ResponseObservable } from 'ngx-http-annotations';
import { Injectable } from '@angular/core';
import RestConfig from 'app/core/configs/rest.config';
interface GoodsItem {
id: number,
name: string,
price: number,
sales?: boolean;
desc?: string;
children?: Array<GoodsItem>;
}
export class SomeRestService {
getGoods( /* Object with queryParams { [name: string]: [value: any] } */ queryObj?: any): any {}
getGoodsBySomeParam( /* ...?sales= */ isSold: boolean): any {}
getGoodsItemById( itemId: number): any {}
/* Few path params */
getChildrenOfSomeGoods( id: number,
childId: number
isSold: boolean,
some: any): any {}
createGoods( /* Body of POST request */ goodsObject: GoodsItem): any {}
removeGoodsById( itemId: number): any {}
/**
* getPostForUserId(3, 2) : call the the url /posts?userId=2 and only take 3 results
*/
public getPostForUserId(number: number, userId: number, res: Observable<any> = undefined): Observable<any> {
return res.pipe(map((response) => response.slice(0, number)));
}
}
```
3) Call the request method from component
```typescript
import { Component, OnInit } from '@angular/core';
import { SomeRestService } from './some-rest.service';
export class TestComponent implements OnInit {
constructor(private someRestService: SomeRestService){}
ngOnInit() {
this.someRestService
.getGoods()
.subscribe( goods => console.log(goods) );
}
}
```
### Description
Available annotations:
1) Request methods
, , , , , , - marks methods implementing the corresponding requests
2) Added settings
- - set path of url for request. Combined class annotation value and current method . Path params passed with ":". For example
- - set headers for request (if annotate class, then all class methods getting this headers. method Headers merge with class Headers)
- - setting expected response type. By default Reponse transformed by .json() method
- - setting http observes.
3) Parameters
- (or ) - pass current parameter by name to collected url. Example: someFunc( itemId: number) {}
- - pass body object into request. Ex.: someMethod( bodyObject: any){}
- - pass single query parameters into request. Ex.: someMethod( a: any, b: any) {}. someMethod(1, 2) -> ..requested_url..?a=1&b=2
- - pass object with few query params. Ex.: someMethod( queryObj: any){}. someMethod({x: 1, y: 2, z: 3}) -> ..requested_url..?x=1&y=2&z=3
- - specify in witch function params, the response observable will be added. Ex.: someMethod( res: Observable<any> = undefined){ /* transform request */ return res; }. need to initialise as undefined to pass compile error, and return a response.
#### Transform response with all rxjs function
By adding the parameters you can specify, where add the observable response,
```typescript
/**
* getPostForUserId(3, 2) : call the the url /posts?userId=2 and only take 3 results
*/
public getPostForUserId(number: number, userId: number, res: Observable<any> = undefined): Observable<any> {
return res.pipe(map((response) => response.slice(0, number)));
}
```
### Mocks calls
To have a feature to enable mocks api. When enabled, will call directly the function rather than call the http request.
To enable Mocks : in a module provider use this :
```typescript
providers: [{ provide: HTTP_ANNOTATIONS_USE_MOCKS, useValue: true }]
```
You can specify a boolean value, or have a specific function, that will be used to know if the apps will use mock.
This could help you to define mock only for specific call.
```typescript
providers: [{ provide: HTTP_ANNOTATIONS_USE_MOCKS, useValue: (url, requestType, params, args): boolean => {
console.log('useMock : ', url, requestType, params, args);
return requestType === 'Get' ? true : false;
} }]
```
define your mocks by return a fake observable, with your mock data.
```typescript
public getPost( id: number): Observable<any> {
return of([{id: id, title: 'mock true'}]);
}
```
### Change logs
0.6.x
-> updates to the latest versions of Angular
-> Rename library to ngx-http-annotations
-> add to transform response.
0.6.2 et 0.6.3
-> update to build the library with angular, to avoid error when build in --prod
0.7.x
-> Add a mock feature.
-> Update dependency to latest
0.7.3
-> Add delay: Add a beta feature, to add a delay to all requests, or have a function that returns this delay. This could be useful, in the mock feature. By default, all mock, will have a default delay. But could be also added without mock, to simulate long request.
-> Use all httpClient methods rather than use request method, use the corresponding method (get, put, delete ...). In order, to avoid issue with request method that throw a first empty error.
-> Update dependencies: Update to version 13 of Angular.
0.8.0
-> Updates to Angular 16, and compile libs to ivy
-> change to nx workspace
-> Add unit tests
### Source and issues
Code are located in github : https://github.com/manudss/ngx-http-annotations