Skip to content

Instantly share code, notes, and snippets.

@suissa
Created May 24, 2019 15:04
Show Gist options
  • Save suissa/c33b9db3e12e1252ad33d547f9403b47 to your computer and use it in GitHub Desktop.
Save suissa/c33b9db3e12e1252ad33d547f9403b47 to your computer and use it in GitHub Desktop.
Exemplo de uma API com esse LIXO do TS
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { NotificationsService } from 'angular2-notifications';
import { Observable } from 'rxjs/Observable';
import { environment } from 'environments/environment';
import { Router } from '@angular/router';
import { stringify } from 'querystring';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiService {
public version = 1;
public host = environment.apiUrl;
constructor(
public http: Http,
public router: Router,
public notification: NotificationsService,
) { }
public setVersion(version: number) {
this.version = version;
}
listConsortiumFromMySQL() {
const url = `https://app.consorciocred.com/suissa/api/cotas/consortium/`
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.get(url, { headers })
}
localizeCPF(cpf) {
const url = `https://app.consorciocred.com/suissa/api/datajus/localize/cpf/${cpf}`
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.get(url, { headers })
}
listCotas(url) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.get(url, { headers })
}
createCota(url, cota) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.post(url, JSON.stringify(cota), { headers })
}
startBackup(url) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.post(url, JSON.stringify({}), { headers })
}
stopBackup(url) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.post(url, JSON.stringify({}), { headers })
}
getBackup(url) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.post(url, JSON.stringify({}), { headers })
}
postBackup(url) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.post(url, JSON.stringify({}), { headers })
}
getDatabases(url) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.get(url, { headers })
}
getStatus(url) {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.get(url, { headers })
}
public getEndpoint(path?: string) {
return `${this.host}/${this.version}${path || ''}`;
}
public getToken() {
if (localStorage.getItem('sessionid')) {
return `session ${localStorage.getItem('sessionid')}`;
}
return null;
}
defaultCatch(res: Response|string, scope): string {
if (typeof scope.sending !== 'undefined') {
scope.sending = false;
}
if (typeof res === 'string' && res.length > 0) {
try {
const parsed = JSON.parse(res);
return parsed.join ? parsed.join('.\n') + '.' : parsed;
} catch (e) {
console.error(`Error: ${e.message} of "${res}"`);
return 'Não foi possível finalizar esta ação.';
}
} else if (typeof res === 'object' && res.status === 401) {
return 'Ação não autorizada';
} else if (typeof res === 'object' && res.status < 500) {
return res.json().join('.\n') + '.';
} else {
return 'Estamos passando por instabilidade no momento, tente novamente mais tarde.';
}
}
getReport(route: string, params?: object, target?: string, download?: boolean) {
let url = `${this.host}/${this.version}/${route}?session=${localStorage.getItem('sessionid')}&download=${!!download}`;
if (params) {
url += `&${stringify(params)}`;
}
window.open(url, target);
}
get(route: string, params?: object): Observable<Response> {
let url = `${this.host}/${this.version}/${route}`;
if (params) {
url += `${route.indexOf('?') === -1 ? '?' : '&'}${stringify(params)}`;
}
return this.http.get(url, { headers: this.getHeader() })
.map((res: Response) => res)
.catch((res, caught) => {
if (res.status === 502) {
this.notification.error('Oops', 'Estamos passando por instabilidade no momento, tente novamente mais tarde');
}
if (res.status === 401) {
this.notification.error('Oops', 'Acesso não autorizado, faça login ou crie sua conta');
localStorage.removeItem('sessionid');
localStorage.removeItem('user');
this.router.navigate(['/login']);
// const body = res.json();
// if (body.plan_status === 'pending') {
// localStorage.removeItem('sessionid');
// localStorage.removeItem('user');
// this.router.navigate(['/login']);
// alert('Você ainda não pagou a sua primeira mensalidade!');
// }
}
return [];
});
}
post(route: string, body?: object): Observable<Response> {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.post(`${this.host}/${this.version}/${route}`, JSON.stringify(body), { headers })
.map((res: Response) => res);
}
put(route: string, body?: object): Observable<Response> {
const headers = this.getHeader({ 'Content-Type': 'application/json' });
return this.http.put(`${this.host}/${this.version}/${route}`, JSON.stringify(body), { headers })
.map((res: Response) => res);
}
delete(route: string): Observable<Response> {
return this.http.delete(`${this.host}/${this.version}/${route}`, { headers: this.getHeader() })
.map((res: Response) => res);
}
public getHeader(opts?: object) {
const headers = new Headers(opts);
if (localStorage.getItem('sessionid')) {
headers.append('Authorization', this.getToken());
}
return headers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment