Created
July 13, 2017 01:06
-
-
Save debuggerpk/0c04c5d543bd557accad49ae4640df0e to your computer and use it in GitHub Desktop.
Base Rest Service for angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Headers, RequestOptionsArgs, Response, Request } from '@angular/http'; | |
import { Observable } from 'rxjs/Observable'; | |
interface IRestConfig { | |
baseHeaders?: Headers; | |
baseUrl: string; | |
path?: string; | |
} | |
interface IRestQuery { | |
[key: string]: boolean | number | string; | |
} | |
interface IRestConfig { | |
apiBaseUrl: string, | |
endPoint: string, | |
} | |
interface IHttp { | |
delete: (url: string, options?: RequestOptionsArgs) => Observable<Response>; | |
get: (url: string, options?: RequestOptionsArgs) => Observable<Response>; | |
head: (url: string, options?: RequestOptionsArgs) => Observable<Response>; | |
patch: (url: string, body: any, options?: RequestOptionsArgs) => Observable<Response>; | |
post: (url: string, body: any, options?: RequestOptionsArgs) => Observable<Response>; | |
put: (url: string, body: any, options?: RequestOptionsArgs) => Observable<Response>; | |
request: (url: string | Request, options?: RequestOptionsArgs) => Observable<Response>; | |
} | |
export abstract class BaseRestService { | |
private _base: string; | |
private _path: string; | |
protected http: IHttp; | |
constructor(http: IHttp, config: IRestConfig) { | |
this._base = config.apiBaseUrl.replace(/\/$/, ''); | |
this._path = config.path.replace(/^\//, ''); | |
this._path = config.path; | |
this.http = http; | |
} | |
public save(obj: any): Observable<any> { | |
if (!!obj.id) { | |
const url = this.buildUrl(obj.id); | |
return this.http.put(url, obj).map(r => r.json()); | |
} else { | |
const url = this.buildUrl(); | |
return this.http.post(url, obj).map(r => r.json()); | |
} | |
} | |
protected buildUrl(id?: number | string): string { | |
let url: string = (this._path) ? `${this._path}/` : ''; | |
url = (id) ? `${url}${id}/` : ''; | |
url = `${this._base}/${url}`; | |
return url; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment