Refactor request service

- Add http post and postgraphql methods to base service
master
Trivernis 5 years ago
parent 99f1a315ef
commit 76adff40eb

@ -51,6 +51,7 @@ export class LoginComponent implements OnInit {
});
}, (error: IErrorResponse) => {
if (error.error) {
console.error(error);
this.loginError(error);
}
});

@ -5,10 +5,10 @@ import {RequestService} from '../../services/request/request.service';
import {SettingsService} from '../../services/settings/settings.service';
import {environment} from 'src/environments/environment';
import {Levellist} from 'src/app/models/levellist';
import {Http} from '@angular/http';
import {Router} from '@angular/router';
import {User} from 'src/app/models/user';
import {OverlayContainer} from '@angular/cdk/overlay';
import {LoginService} from '../../services/login/login.service';
@Component({
selector: 'app-main-navigation',
@ -21,9 +21,10 @@ export class MainNavigationComponent implements OnInit {
public overlayContainer: OverlayContainer,
private data: DatasharingService,
private settingsService: SettingsService,
private requestservice: RequestService,
private requestService: RequestService,
private breakpointObserver: BreakpointObserver,
private http: Http, private router: Router,
private loginService: LoginService,
private router: Router,
) {
this.overlay = overlayContainer.getContainerElement();
}
@ -123,50 +124,46 @@ export class MainNavigationComponent implements OnInit {
localStorage.setItem('theme', theme);
}
/**
* Logs out
*/
logout() {
const url = environment.graphQLUrl;
const headers = new Headers();
headers.set('Content-Type', 'application/json');
const body = {
query: `mutation {
logout
}`
};
this.http.post(url, body).subscribe(response => {
this.loginService.logout().subscribe(() => {
this.loggedIn = false;
const user = new User();
user.loggedIn = false;
this.data.changeUserInfo(user);
this.router.navigate(['login']);
});
this.loggedIn = false;
const user = new User();
user.loggedIn = false;
this.data.changeUserInfo(user);
this.router.navigate(['login']);
}
/**
* Accepts a request
* @param id
*/
acceptRequest(id: number) {
const headers = new Headers();
headers.set('Content-Type', 'application/json');
this.http.post(environment.graphQLUrl, this.requestservice.buildJsonAcceptRequest(id))
.subscribe(response => {
for (let i = 0; i < this.user.receivedRequests.length; i++) {
if (this.user.receivedRequests[i].senderUserID === id) {
this.user.receivedRequests.splice(i, 1);
return;
}
this.requestService.acceptRequest(id).subscribe(response => {
for (let i = 0; i < this.user.receivedRequests.length; i++) {
if (this.user.receivedRequests[i].senderUserID === id) {
this.user.receivedRequests.splice(i, 1);
return;
}
});
}
});
}
/**
* Denys a request
* @param id
*/
denyRequest(id: number) {
const headers = new Headers();
headers.set('Content-Type', 'application/json');
this.http.post(environment.graphQLUrl, this.requestservice.buildJsonDenyRequest(id))
.subscribe(response => {
for (let i = 0; i < this.user.receivedRequests.length; i++) {
if (this.user.receivedRequests[i].senderUserID === id) {
this.user.receivedRequests.splice(i, 1);
return;
}
this.requestService.denyRequest(id).subscribe(() => {
for (let i = 0; i < this.user.receivedRequests.length; i++) {
if (this.user.receivedRequests[i].senderUserID === id) {
this.user.receivedRequests.splice(i, 1);
return;
}
});
}
});
}
}

@ -1,7 +1,8 @@
import {Injectable} from '@angular/core';
import { HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {delay, mergeMap, retryWhen} from 'rxjs/operators';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {delay, mergeMap, retry, retryWhen} from 'rxjs/operators';
import {Observable, of, throwError} from 'rxjs';
import {environment} from '../../environments/environment';
const httpTooManyCode = 429;
const httpHeaderRateRetry = 'Retry-After';
@ -11,11 +12,33 @@ const httpHeaderRateRetry = 'Retry-After';
})
export abstract class BaseService {
protected headers: HttpHeaders;
protected constructor() {
protected constructor(protected http?: HttpClient) {
this.headers = new HttpHeaders();
this.headers.set('Content-Type', 'application/json');
}
/**
* Does a http post request
* @param url
* @param body
* @param options
* @param retryLimit
*/
protected post<T>(url: string, body: any, options?: any, retryLimit: number = 3): Observable<any | T> {
return this.http.post<T>(url, body, Object.assign({headers: this.headers}, options))
.pipe(this.retryRated(retryLimit));
}
/**
* Does a http post to the graphql url
* @param body
* @param options
* @param retryLimit
*/
protected postGraphql<T>(body: any, options?: any, retryLimit: number = 3): Observable<any | T> {
return this.post<T>(environment.graphQLUrl, body, options, retryLimit);
}
/**
* Retries a request according to the rate limit
* @param maxRetry

@ -1,12 +0,0 @@
import {TestBed} from '@angular/core/testing';
import {DocumentService} from './document.service';
describe('DocumentService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: DocumentService = TestBed.get(DocumentService);
expect(service).toBeTruthy();
});
});

@ -1,39 +0,0 @@
import {Injectable} from '@angular/core';
import {Socket} from 'ngx-socket-io';
import {Document} from '../models/document';
@Injectable({
providedIn: 'root'
})
export class DocumentService {
currentDocument = this.socket.fromEvent<Document>('document');
documents = this.socket.fromEvent<string[]>('documents');
constructor(private socket: Socket) {
}
getDocument(id: string) {
this.socket.emit('getDoc', id);
}
newDocument() {
this.socket.emit('addDoc', {id: this.docId(), doc: ''});
}
editDocument(document: Document) {
this.socket.emit('editDoc', document);
}
private docId() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
}

@ -99,8 +99,8 @@ export enum Sort {
})
export class FeedService extends BaseService {
constructor(private http: HttpClient) {
super();
constructor(http: HttpClient) {
super(http);
}
public postsAvailable = new BehaviorSubject<boolean>(true);
@ -159,7 +159,7 @@ export class FeedService extends BaseService {
* @param body
*/
private createPostRequest(body: { variables: any; query: string }) {
return this.http.post(environment.graphQLUrl, body, {headers: this.headers})
return this.postGraphql(body, null, 0)
.pipe(tap(response => {
if (this.activePostList === Sort.NEW) {
const updatedPosts = this.posts.getValue();
@ -180,7 +180,7 @@ export class FeedService extends BaseService {
}
};
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}).pipe(this.retryRated());
return this.postGraphql(body);
}
/**
@ -194,7 +194,7 @@ export class FeedService extends BaseService {
}
};
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}).pipe(this.retryRated());
return this.postGraphql(body);
}
/**

@ -137,5 +137,4 @@ export class GroupService {
};
return this.http.post(environment.graphQLUrl, body);
}
}

@ -42,13 +42,17 @@ const graphqlQuery = `mutation($email: String!, $pwHash: String!) {
}
}`;
const logoutGqlQuery = `mutation {
logout
}`;
@Injectable({
providedIn: 'root'
})
export class LoginService extends BaseService {
constructor(private http: HttpClient, private datasharingService: DatasharingService) {
super();
constructor(http: HttpClient, private datasharingService: DatasharingService) {
super(http);
}
/**
@ -65,17 +69,33 @@ export class LoginService extends BaseService {
};
}
/**
* Builds a logout request
*/
public static buildLogoutBody(): any {
return {
query: logoutGqlQuery
};
}
/**
* Performs a login request and returns the data of the logged in user.
* @param login
*/
public login(login: Login) {
const body = LoginService.buildRequestBody(login);
return this.http.post<ILoginRequestResult>(environment.graphQLUrl, body, {headers: this.headers})
return this.postGraphql<ILoginRequestResult>(body, null, 0)
.pipe(tap(response => {
const user = new User();
user.assignFromResponse(response.data.login);
this.datasharingService.changeUserInfo(user);
}));
}
/**
* Loggs out
*/
public logout() {
return this.postGraphql(LoginService.buildLogoutBody());
}
}

@ -51,8 +51,8 @@ const graphqlGetProfileQuery = `query($userId: ID) {
})
export class ProfileService extends BaseService {
constructor(private http: HttpClient) {
super();
constructor(http: HttpClient) {
super(http);
}
public proflile: Subject<any> = new Subject();
@ -77,8 +77,7 @@ export class ProfileService extends BaseService {
public getUserData(userId: string) {
const headers = new Headers();
headers.set('Content-Type', 'application/json');
this.http.post(environment.graphQLUrl, ProfileService.buildGetProfileBody(userId))
.pipe(this.retryRated())
this.postGraphql(ProfileService.buildGetProfileBody(userId))
.subscribe(result => {
this.proflile.next(this.getProfileData(result));
return this.proflile;

@ -1,18 +1,74 @@
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {DatasharingService} from '../datasharing.service';
import {Router} from '@angular/router';
import {environment} from 'src/environments/environment';
import {User} from 'src/app/models/user';
import {GroupInfo} from 'src/app/models/groupinfo';
import {HttpClient} from '@angular/common/http';
import {BaseService} from '../base.service';
const denyRequestGqlQuery = `mutation($id: ID!) {
denyRequest(sender: $id, type: FRIENDREQUEST)
}`;
const acceptRequestGqlQuery = `mutation($id: ID!) {
acceptRequest(sender: $id, type: FRIENDREQUEST)
}`;
const sendRequestGqlQuery = `mutation($id: ID!, $type: RequestType) {
sendRequest(receiver: $id, type: $type) {
id
}
}`;
@Injectable({
providedIn: 'root'
})
export class RequestService {
export class RequestService extends BaseService {
constructor(http: HttpClient, private data: DatasharingService, private router: Router) {
super(http);
}
private static buildDenyRequestBody(id: number): any {
return {
query: denyRequestGqlQuery
, variables: {
id
}
};
}
private static buildAcceptRequestBody(id: number): any {
return {
query: acceptRequestGqlQuery
, variables: {
id
}
};
}
constructor(private http: Http, private data: DatasharingService, private router: Router) {
private static buildJoinGroupBody(id: number): any {
return {
query: `mutation($id: ID!) {
joinGroup(id: $id) {
id
}
}`
, variables: {
id
}
};
}
private static buildSendRequestBody(id: number, type: String): any {
return {
query: sendRequestGqlQuery
, variables: {
id,
type
}
};
}
public isAllowedToSendRequest(userID: number, self: User): boolean {
@ -55,74 +111,39 @@ export class RequestService {
return true;
}
/**
* Sends a send request
* @param user
*/
public sendFriendRequest(user: User) {
this.data.addSentRequestUserID(user.userID);
const headers = new Headers();
headers.set('Content-Type', 'application/json');
this.http.post(environment.graphQLUrl, this.buildJsonRequest(user.userID, 'FRIENDREQUEST'))
.subscribe(response => {
this.postGraphql(RequestService.buildSendRequestBody(user.userID, 'FRIENDREQUEST'))
.subscribe(() => {
this.data.addSentRequestUserID(user.userID);
});
}
/**
* Joins a group
* @param group
*/
public joinGroup(group: GroupInfo) {
const headers = new Headers();
headers.set('Content-Type', 'application/json');
this.http.post(environment.graphQLUrl, this.buildJsonJoinGroup(group.id))
.subscribe(response => {
});
this.postGraphql(RequestService.buildJoinGroupBody(group.id))
.subscribe();
}
public buildJsonRequest(id_: number, type_: String): any {
const body = {
query: `mutation($id: ID!, $type: RequestType) {
sendRequest(receiver: $id, type: $type) {
id
}
}`
, variables: {
id: id_,
type: type_
}
};
return body;
/**
* Accepts a request
* @param id
*/
public acceptRequest(id: number) {
return this.postGraphql(RequestService.buildAcceptRequestBody(id));
}
public buildJsonJoinGroup(id_: number): any {
const body = {
query: `mutation($id: ID!) {
joinGroup(id: $id) {
id
}
}`
, variables: {
id: id_
}
};
return body;
/**
* Denys a request
* @param id
*/
public denyRequest(id: number) {
return this.postGraphql(RequestService.buildDenyRequestBody(id));
}
public buildJsonAcceptRequest(id_: number): any {
const body = {
query: `mutation($id: ID!) {
acceptRequest(sender: $id, type: FRIENDREQUEST)
}`
, variables: {
id: id_
}
};
return body;
}
public buildJsonDenyRequest(id_: number): any {
const body = {
query: `mutation($id: ID!) {
denyRequest(sender: $id, type: FRIENDREQUEST)
}`
, variables: {
id: id_
}
};
return body;
}
}

@ -41,8 +41,8 @@ const graphqlQuery = `query($query: String!, $first: Int, $offset: Int) {
providedIn: 'root'
})
export class SearchService extends BaseService {
constructor(private http: HttpClient, private data: DatasharingService, private router: Router) {
super();
constructor(http: HttpClient, private data: DatasharingService, private router: Router) {
super(http);
}
/**
@ -101,7 +101,7 @@ export class SearchService extends BaseService {
*/
public search(query: string): Observable<ISearchRequestResult> {
const body = SearchService.buildRequestBody(query);
return this.http.post<ISearchRequestResult>(environment.graphQLUrl, body, {headers: this.headers})
return this.postGraphql<ISearchRequestResult>(body)
.pipe(this.retryRated());
}
}

@ -40,8 +40,8 @@ const getSelfGraphqlQuery = `{
})
export class SelfService extends BaseService {
constructor(private http: HttpClient, private data: DatasharingService) {
super();
constructor(http: HttpClient, private data: DatasharingService) {
super(http);
}
/**
@ -61,8 +61,7 @@ export class SelfService extends BaseService {
const headers = new Headers();
headers.set('Content-Type', 'application/json');
return this.http.post(url, SelfService.buildGetSelfBody(), {headers: this.headers})
.pipe(this.retryRated())
return this.postGraphql(SelfService.buildGetSelfBody())
.pipe(tap(response => {
this.updateUserInfo(response);
}));
@ -75,7 +74,7 @@ export class SelfService extends BaseService {
public changeProfilePicture(file: any) {
const formData: any = new FormData();
formData.append('profilePicture', file);
return this.http.post<IFileUploadResult>(environment.greenvironmentUrl + '/upload', formData)
return this.post<IFileUploadResult>(environment.greenvironmentUrl + '/upload', formData, null, 0)
.pipe(this.retryRated());
}

@ -14,8 +14,8 @@ const graphqlCreateGroupQuery = `mutation($name: String!) {
})
export class SocialService extends BaseService {
constructor(private http: HttpClient) {
super();
constructor(http: HttpClient) {
super(http);
}
/**
@ -36,7 +36,6 @@ export class SocialService extends BaseService {
*/
createGroup(name: string) {
const body = SocialService.buildGroupCreateBody(name);
return this.http.post(environment.graphQLUrl, body, {headers: this.headers})
.pipe(this.retryRated());
return this.postGraphql(body);
}
}

Loading…
Cancel
Save