Skip to content

Commit e98484c

Browse files
Angular 2 -> API Base big refactor
- You can add to your angular without doing changes - Removed all store dependences - Removed handle error
1 parent 70844fa commit e98484c

File tree

2 files changed

+43
-184
lines changed

2 files changed

+43
-184
lines changed

ApiBase/api-base.native.service.ts

Lines changed: 23 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,10 @@
1+
import { HttpClient } from '@angular/common/http';
12
import { Injectable } from '@angular/core';
2-
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
3-
import { Observable } from 'rxjs/Observable';
4-
import { catchError, map } from 'rxjs/operators';
5-
6-
import { Store } from '@ngrx/store';
7-
import { AppState } from '@app/store/app.reducers';
83
import { HTTP } from '@ionic-native/http/ngx';
9-
import { ApiBaseService } from './api-base.service';
104
import { from } from 'rxjs/internal/observable/from';
11-
12-
export interface APIError {
13-
error: any;
14-
errorText: string;
15-
}
5+
import { Observable } from 'rxjs/Observable';
6+
import { map } from 'rxjs/operators';
7+
import { ApiBaseService } from './api-base.service';
168

179
/**
1810
* Implementation of angular-http
@@ -22,48 +14,48 @@ export interface APIError {
2214
*/
2315
@Injectable()
2416
export class ApiBaseNativeService extends ApiBaseService {
25-
constructor(
26-
protected http: HttpClient,
27-
protected store$: Store<AppState>,
28-
protected httpNative: HTTP
29-
) {
30-
super(http, store$);
17+
constructor(protected http: HttpClient, protected httpNative: HTTP) {
18+
super(http);
3119
}
3220

3321
public doGet(url, params = null, data = null): Observable<any> {
3422
// const options = this.getOptions(url, params, data);
3523
url = this.parseURLParams(url, params);
3624
return from(
37-
this.httpNative.get(this.serverURL + url, {}, this.httpHeadersPlain)
38-
).pipe(
39-
map((response) => JSON.parse(response.data)),
40-
catchError((error) => this.handleError(error))
41-
);
25+
this.httpNative.get(this.serverURL + url, {}, this.httpHeadersPlain),
26+
).pipe(map((response) => JSON.parse(response.data)));
4227
}
4328

4429
public doPost(url, params, data): Observable<any> {
4530
// const options = this.getOptions(url, params, data);
31+
url = this.parseURLParams(url, params);
4632
this.setHeaders();
4733
url = this.parseURLParams(url, params);
48-
return from(this.httpNative.post(this.serverURL + url, data, {})).pipe(
49-
catchError((error) => this.handleError(error))
50-
);
34+
return from(this.httpNative.post(this.serverURL + url, data, {})).pipe();
5135
}
5236

5337
public doPut(url, params, data): Observable<any> {
5438
// const options = this.getOptions(url, params, data);
5539
url = this.parseURLParams(url, params);
5640
return from(
57-
this.httpNative.put(this.serverURL + url, data, this.httpHeadersPlain)
58-
).pipe(catchError((error) => this.handleError(error)));
41+
this.httpNative.put(this.serverURL + url, data, this.httpHeadersPlain),
42+
);
43+
}
44+
45+
public doPatch(url, params, data): Observable<any> {
46+
// const options = this.getOptions(url, params, data);
47+
url = this.parseURLParams(url, params);
48+
return from(
49+
this.httpNative.patch(this.serverURL + url, data, this.httpHeadersPlain),
50+
);
5951
}
6052

6153
public doDel(url, params, data = null): Observable<any> {
6254
// const options = this.getOptions(url, params, data);
6355
url = this.parseURLParams(url, params);
6456
return from(
65-
this.httpNative.delete(this.serverURL + url, {}, this.httpHeadersPlain)
66-
).pipe(catchError((error) => this.handleError(error)));
57+
this.httpNative.delete(this.serverURL + url, {}, this.httpHeadersPlain),
58+
);
6759
}
6860

6961
public generateFormData(values: any): FormData {
@@ -87,20 +79,8 @@ export class ApiBaseNativeService extends ApiBaseService {
8779
this.httpNative.setHeader(
8880
'*',
8981
String(key),
90-
String(this.httpHeadersPlain[key])
82+
String(this.httpHeadersPlain[key]),
9183
);
9284
}
9385
}
94-
95-
protected handleError(error: HttpErrorResponse): Observable<APIError> {
96-
console.error('ERROR CATCHED', error);
97-
return super.handleError(error);
98-
}
99-
100-
protected getOptions(url, params = null, data = null) {
101-
return {
102-
headers: this.httpHeaders,
103-
// params: this.parseURLParams(url, params),
104-
};
105-
}
10686
}

ApiBase/api-base.service.ts

Lines changed: 20 additions & 141 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
1+
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
12
import { Injectable } from '@angular/core';
2-
import {
3-
HttpClient,
4-
HttpHeaders,
5-
HttpErrorResponse,
6-
HttpParams,
7-
} from '@angular/common/http';
83
import { Observable } from 'rxjs/Observable';
9-
import { Subscription } from 'rxjs/internal/Subscription';
10-
import { catchError } from 'rxjs/operators';
11-
import { throwError } from 'rxjs/internal/observable/throwError';
12-
134
import { environment } from 'src/environments/environment';
14-
import { Store } from '@ngrx/store';
15-
import { AppState } from '@app/store/app.reducers';
16-
import * as AuthActions from '@app/store/auth/auth.actions';
17-
18-
const PROD_MODE = environment.production;
19-
20-
export interface APIError {
21-
error: any;
22-
errorText: string;
23-
}
245

256
export interface HttpOptions {
267
headers?:
@@ -62,31 +43,11 @@ export class ApiBaseService {
6243
* All headers to re-generate httpHeaders (setters and getters not working)
6344
*/
6445
protected httpHeadersPlain: any = {
65-
'Content-Type': 'application/json',
6646
'Access-Control-Allow-Origin': '*',
6747
// 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
6848
};
6949

70-
protected authStoreObserver$: Subscription;
71-
72-
constructor(protected http: HttpClient, protected store$: Store<AppState>) {
73-
this.handleError = this.handleError.bind(this);
74-
// this.generateHeaders();
75-
this.subscribeToStore(); // setToken call generateHeaders
76-
}
77-
78-
subscribeToStore() {
79-
// TODO: Optimize this to avoid be called on every "auth", only for "auth_token"
80-
this.authStoreObserver$ = this.store$
81-
.select('auth')
82-
.subscribe((data: any) => {
83-
if (!!data && !!data.token) {
84-
this.setToken(data.token.token);
85-
} else {
86-
this.setToken(null);
87-
}
88-
});
89-
}
50+
constructor(protected http: HttpClient) {}
9051

9152
setToken(token: string): void {
9253
if (token) {
@@ -110,10 +71,7 @@ export class ApiBaseService {
11071
const options = this.getOptions(customOptions);
11172
url = this.parseURLParams(url, params);
11273
// TODO: Add support to http.get<RESPONSETYPE>() or on .subscribe
113-
return this.http.get(this.serverURL + url, options).pipe(
114-
// retry(1),
115-
catchError((error) => this.handleError(error)),
116-
);
74+
return this.http.get(this.serverURL + url, options);
11775
}
11876

11977
public doPost(
@@ -124,9 +82,7 @@ export class ApiBaseService {
12482
): Observable<any> {
12583
const options = this.getOptions(customOptions);
12684
url = this.parseURLParams(url, params);
127-
return this.http
128-
.post(this.serverURL + url, data, options)
129-
.pipe(catchError((error) => this.handleError(error)));
85+
return this.http.post(this.serverURL + url, data, options);
13086
}
13187

13288
public doPut(
@@ -137,9 +93,7 @@ export class ApiBaseService {
13793
): Observable<any> {
13894
const options = this.getOptions(customOptions);
13995
url = this.parseURLParams(url, params);
140-
return this.http
141-
.put(this.serverURL + url, data, options)
142-
.pipe(catchError((error) => this.handleError(error)));
96+
return this.http.put(this.serverURL + url, data, options);
14397
}
14498

14599
public doOptions(
@@ -150,9 +104,7 @@ export class ApiBaseService {
150104
): Observable<any> {
151105
const options = this.getOptions(customOptions);
152106
url = this.parseURLParams(url, params);
153-
return this.http
154-
.options(this.serverURL + url, options)
155-
.pipe(catchError((error) => this.handleError(error)));
107+
return this.http.options(this.serverURL + url, options);
156108
}
157109

158110
public doPatch(
@@ -163,9 +115,7 @@ export class ApiBaseService {
163115
): Observable<any> {
164116
const options = this.getOptions(customOptions);
165117
url = this.parseURLParams(url, params);
166-
return this.http
167-
.patch(this.serverURL + url, options)
168-
.pipe(catchError((error) => this.handleError(error)));
118+
return this.http.patch(this.serverURL + url, options);
169119
}
170120

171121
public doDelete(
@@ -176,16 +126,15 @@ export class ApiBaseService {
176126
): Observable<any> {
177127
const options = this.getOptions(customOptions);
178128
url = this.parseURLParams(url, params);
179-
return this.http
180-
.delete(this.serverURL + url, options)
181-
.pipe(catchError((error) => this.handleError(error)));
129+
return this.http.delete(this.serverURL + url, options);
182130
}
183131

184132
public generateFormData(values: any): FormData {
185133
const form = new FormData();
186134
for (const key in values) {
187135
if (values[key]) {
188-
form.append(key, values[key]);
136+
const element = values[key];
137+
form.append(key, element, element?.name);
189138
}
190139
}
191140
return form;
@@ -198,52 +147,17 @@ export class ApiBaseService {
198147
this.httpHeaders = new HttpHeaders(this.httpHeadersPlain);
199148
}
200149

201-
protected handleError(error: HttpErrorResponse): Observable<APIError> {
202-
let errorText;
203-
const errorData = error.error;
204-
205-
if (error.status === 401) {
206-
this.store$.dispatch(AuthActions.logOut());
207-
return throwError({
208-
error,
209-
errorText: 'Su sesión ha caducado. Por favor, inicie sesión de nuevo',
210-
} as APIError);
211-
}
212-
213-
if (!errorData) {
214-
errorText = error.message;
215-
} else if (errorData.errors) {
216-
if (typeof errorData.errors === 'string') {
217-
errorText = errorData.errors;
218-
} else {
219-
errorText = this.readErrorArray(errorData.errors);
220-
}
221-
} else if (errorData.error) {
222-
errorText = errorData.error[0];
223-
} else if (errorData.title) {
224-
errorText = errorData.title;
225-
} else if (!(errorData instanceof ProgressEvent) && !errorData.srcElement) {
226-
errorText = this.readErrorArray(errorData);
227-
} else {
228-
errorText =
229-
'URL could not be loaded. Please, check your internet connection.';
230-
}
231-
232-
if (!PROD_MODE) {
233-
console.groupCollapsed('Response error:');
234-
console.error(errorText);
235-
console.error(error);
236-
console.groupEnd();
237-
}
238-
239-
return throwError({
240-
error,
241-
errorText,
242-
} as APIError);
243-
}
244-
245150
protected getOptions(customOptions?: Partial<HttpOptions>) {
246-
return Object.assign({ headers: { ...this.httpHeaders } }, customOptions);
151+
if (!customOptions) {
152+
return { headers: this.httpHeaders };
153+
}
154+
return {
155+
...customOptions,
156+
headers: new HttpHeaders({
157+
...this.httpHeadersPlain,
158+
...customOptions?.headers,
159+
}),
160+
};
247161
}
248162

249163
/**
@@ -278,39 +192,4 @@ export class ApiBaseService {
278192
const paramsString = queryParams.toString();
279193
return paramsString !== '' ? url + '?' + queryParams.toString() : url;
280194
}
281-
282-
protected readErrorArray(errors) {
283-
let errorText = 'No se pudo contactar con el servidor';
284-
if (typeof errors === 'object' && 'errorCode' in errors) {
285-
return errors.message;
286-
}
287-
if (typeof errors === 'string' && errors !== '') {
288-
return errors;
289-
}
290-
return errorText;
291-
// tslint:disable-next-line: forin
292-
for (const errorKey in errors) {
293-
if (!errors[errorKey]) {
294-
continue;
295-
}
296-
297-
if (typeof errors[errorKey] !== 'object') {
298-
if (errorText !== '') {
299-
errorText += '<br />';
300-
}
301-
errorText += errorKey + ':' + errors[errorKey];
302-
} else if (Array.isArray(errors[errorKey])) {
303-
for (const errorDetails of errors[errorKey]) {
304-
if (typeof errorDetails === 'object') {
305-
break;
306-
}
307-
if (errorText !== '') {
308-
errorText += '<br />';
309-
}
310-
errorText += '- ' + errorDetails;
311-
}
312-
}
313-
}
314-
return errorText;
315-
}
316195
}

0 commit comments

Comments
 (0)