Skip to content

Instantly share code, notes, and snippets.

@dvsingh9
Created May 2, 2020 17:08
Show Gist options
  • Save dvsingh9/03be5fd31443343d54894b12cfeb05d7 to your computer and use it in GitHub Desktop.
Save dvsingh9/03be5fd31443343d54894b12cfeb05d7 to your computer and use it in GitHub Desktop.
TypeScript Generics - Base Service for http services
import * as _ from 'lodash';
import {Observable} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {share} from 'rxjs/operators';
import {PageableResponse} from '../modal/pageable-response.modal';
import {Search} from '../modal/search.modal';
export class BaseService<T> {
private http: HttpClient;
private url: string;
constructor(http: HttpClient, url: string) {
this.url = url;
this.http = http;
}
searchAndSort(page: number, size: number, sort: string, order: string, searchList?: Search[]): Observable<PageableResponse<T>> {
let params = new HttpParams();
let url = this.url + '?page=' + page ;
if (size != null) {
url += '&size=' + size;
}
if (order !== 'desc') {
order = 'asc';
}
if (sort != null) {
url += ('&sort=' + sort + ',' + order);
} else {
url += ('&sort=createdOn,desc');
}
if (searchList && searchList.length > 0) {
_.forEach(searchList, (search) => {
if (search.column && search.content) {
params = params.append(search.column, search.content);
}
});
}
return this.http.get<PageableResponse<T>>(url, { params });
}
count(searchList?: Search[]): Observable<number> {
let params = new HttpParams();
const url = this.url + '/count';
if (searchList && searchList.length > 0) {
const url = this.url + '/count?';
_.forEach(searchList, (search: Search) => {
if (search.column && search.content) {
params = params.append(search.column, search.content);
}
});
}
return this.http.get<number>(url, { params }).pipe(share());
}
getById(id: any): Observable<T> {
const url = this.url + '/' + id;
return this.http.get<T>(url).pipe(share());
}
delete(id: any): Observable<any> {
const url = this.url + '/' + id;
return this.http.delete<any>(url);
}
update(id: any, data: T): Observable<T> {
const url = this.url + '/' + id;
return this.http.put<T>(url, data);
}
create(data: T): Observable<T> {
return this.http.post<T>(this.url, data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment