funky-framadate-front/src/app/core/services/api.service.ts

311 lines
10 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@angular/core';
2020-05-01 19:10:17 +02:00
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { environment } from 'src/environments/environment';
2020-06-12 19:17:39 +02:00
import { Answer } from '../enums/answer.enum';
import { Poll } from '../models/poll.model';
2021-04-28 15:35:08 +02:00
import { HttpClient } from '@angular/common/http';
import { Observable, Subscription } from 'rxjs';
2020-11-13 09:38:42 +01:00
import { ToastService } from './toast.service';
import { LoaderService } from './loader.service';
import { Stack } from '../models/stack.model';
2020-11-09 12:44:24 +01:00
const apiVersion = environment.api.versionToUse;
const currentApiRoutes = environment.api.version[apiVersion];
const apiBaseHref = environment.api.version[apiVersion].baseHref;
const apiEndpoints = environment.api.endpoints;
@Injectable({
providedIn: 'root',
})
export class ApiService {
2020-05-01 19:10:17 +02:00
private axiosInstance: AxiosInstance;
2020-11-09 12:44:24 +01:00
private readonly pollsEndpoint = apiEndpoints.polls.name;
private readonly answersEndpoint = apiEndpoints.polls.answers.name;
private readonly commentsEndpoint = apiEndpoints.polls.comments.name;
private readonly slugsEndpoint = apiEndpoints.polls.slugs.name;
private readonly usersEndpoint = apiEndpoints.users.name;
private readonly usersPollsEndpoint = apiEndpoints.users.polls.name;
private readonly usersPollsSendEmailEndpoint = apiEndpoints.users.polls.sendEmail.name;
private baseHref: string;
private static loaderService: LoaderService;
2020-05-01 19:10:17 +02:00
constructor(private http: HttpClient, private toastService: ToastService, private loaderService: LoaderService) {
this.baseHref = apiBaseHref;
2020-11-09 12:44:24 +01:00
this.axiosInstance = axios.create({ baseURL: apiBaseHref });
2020-05-12 19:16:23 +02:00
this.axiosInstance.defaults.timeout = 2500;
this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/json';
2020-11-13 09:38:42 +01:00
this.axiosInstance.defaults.headers.post['Accept'] = 'application/json';
2020-11-11 12:14:01 +01:00
this.axiosInstance.defaults.headers.post['Charset'] = 'UTF-8';
// this.axiosInstance.defaults.headers.post['Accept-Charset'] = 'UTF-8';
2020-11-13 09:38:42 +01:00
this.axiosInstance.defaults.headers.post['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
2021-04-29 10:17:13 +02:00
this.axiosInstance.defaults.headers.post['Referrer-Policy'] = 'origin-when-cross-origin';
2020-11-13 09:38:42 +01:00
this.axiosInstance.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
2021-04-29 10:17:13 +02:00
this.axiosInstance.defaults.headers.post['Allow-Origin'] = '*';
this.axiosInstance.defaults.headers.post['Access-Control-Allow-Headers'] =
'Origin, X-Requested-With, Content-Type, Accept';
console.log('this.axiosInstance.defaults.headers', this.axiosInstance.defaults.headers);
2020-05-01 19:10:17 +02:00
}
2020-05-12 19:16:23 +02:00
//////////////////////
// CREATE OR UPDATE //
//////////////////////
2021-04-25 12:05:17 +02:00
/////////////////////
/**
* prepare headers like the charset and json type for any call to the backend
* @param bodyContent?
*/
static makeHeaders(bodyContent?: any) {
const headerDict = {
Charset: 'UTF-8',
2021-04-28 15:35:08 +02:00
// 'Content-Type': 'application/json',
// Accept: 'application/json',
'Access-Control-Allow-Origin': '*',
2021-04-25 12:05:17 +02:00
'Content-Type': 'application/json',
2021-04-28 15:35:08 +02:00
mode: 'no-cors',
2021-04-25 12:05:17 +02:00
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Accept,Accept-Language,Content-Language,Content-Type',
2021-04-28 15:35:08 +02:00
// 'Access-Control-Allow-Origin': '*',
2021-04-25 12:05:17 +02:00
};
2021-04-28 15:35:08 +02:00
return {
headers: headerDict,
2021-04-25 12:05:17 +02:00
body: bodyContent,
};
}
2020-11-13 09:38:42 +01:00
public async createPoll(poll: Poll): Promise<Subscription> {
// this.loaderService.setStatus(true);
2021-02-04 16:14:07 +01:00
console.log('createPoll config', poll);
2021-04-25 12:05:17 +02:00
return this.axiosInstance.post(
`${this.baseHref}${currentApiRoutes['api_new_poll']}`,
2021-04-25 12:05:17 +02:00
poll,
ApiService.makeHeaders()
);
}
/**
* send a new vote stack
* @param vote_stack
*/
2021-06-07 11:30:10 +02:00
public sendNewVoteStackOfPoll(vote_stack: Stack): Promise<void> {
// api_new_vote_stack POST ANY ANY /api/v1/poll/{id}/answer
console.log('vote_stack', vote_stack);
console.log('this.baseHref', this.baseHref);
2021-04-29 10:17:13 +02:00
const headers = ApiService.makeHeaders(vote_stack);
console.log('headers', headers);
2021-06-07 11:30:10 +02:00
const url = `${this.baseHref}/vote-stack/`;
2021-04-29 10:17:13 +02:00
const axiosconf = {
2021-04-28 15:35:08 +02:00
url,
method: 'POST',
body: vote_stack,
headers,
};
2021-05-20 14:23:57 +02:00
return this.axiosInstance.post(url, vote_stack);
}
2021-04-25 12:05:17 +02:00
//////////
// READ //
2020-05-12 19:16:23 +02:00
public async createParticipation(
pollId: string,
choiceLabel: string,
pseudo: string,
2020-06-12 19:17:39 +02:00
response: Answer
2020-05-12 19:16:23 +02:00
): Promise<string> {
try {
2020-05-12 19:16:23 +02:00
return await this.axiosInstance.post(`${this.pollsEndpoint}/${pollId}${this.answersEndpoint}`, {
choiceLabel,
pseudo,
response,
2020-05-01 19:10:17 +02:00
});
} catch (error) {
ApiService.handleError(error);
}
}
2020-05-12 19:16:23 +02:00
public async createComment(slug: string, comment: string): Promise<string> {
try {
2020-05-12 19:16:23 +02:00
return await this.axiosInstance.post(`${this.pollsEndpoint}/${slug}${this.commentsEndpoint}`, comment);
} catch (error) {
ApiService.handleError(error);
}
}
//////////
2020-06-25 22:42:26 +02:00
public async getAllAvailablePolls(): Promise<Poll[]> {
2020-05-12 19:16:23 +02:00
// TODO: used for facilities in DEV, should be removed in production
try {
const response: AxiosResponse<Poll[]> = await this.axiosInstance.get<Poll[]>(`${this.pollsEndpoint}`);
2020-06-25 22:42:26 +02:00
return response?.data;
2020-05-12 19:16:23 +02:00
} catch (error) {
ApiService.handleError(error);
2020-05-12 19:16:23 +02:00
}
}
public async getPollByCustomUrl(slug: string): Promise<Poll | undefined> {
2020-05-12 19:16:23 +02:00
try {
2021-06-07 11:30:10 +02:00
console.log('fetch API : asking for poll with custom_url=' + slug);
2020-05-12 19:16:23 +02:00
const response: AxiosResponse<Poll> = await this.axiosInstance.get<Poll>(`${this.pollsEndpoint}/${slug}`);
2020-06-18 16:15:26 +02:00
return response && response.data && !Array.isArray(response.data) ? response.data : undefined;
2020-05-12 19:16:23 +02:00
} catch (error) {
if (error.response?.status === 404) {
return undefined;
} else {
ApiService.handleError(error);
2020-05-12 19:16:23 +02:00
}
}
}
public async getPollByCustomUrlWithHash(slug: string, hash: string): Promise<Poll | undefined> {
2021-04-21 12:17:05 +02:00
try {
const response: AxiosResponse<Poll> = await this.axiosInstance.get<Poll>(
`${this.pollsEndpoint}/${slug}/pass/${hash}`
);
console.log('fetch API : asking for poll with custom_url=' + slug, { response });
2021-04-21 12:17:05 +02:00
return response && response.data && !Array.isArray(response.data) ? response.data : undefined;
} catch (error) {
if (error.response?.status === 404) {
return undefined;
} else {
ApiService.handleError(error);
}
}
}
2020-05-12 19:16:23 +02:00
public async getSlug(slug: string): Promise<boolean> {
try {
// TODO: scenario should be : if we can get this custom_url, it exists. if not, it doesn't. It's just a GET.
2020-05-01 19:10:17 +02:00
const response: AxiosResponse = await this.axiosInstance.get(
`${this.pollsEndpoint}${this.slugsEndpoint}/${slug}`
);
2020-05-01 19:10:17 +02:00
if (response?.status !== 404) {
return false;
}
} catch (error) {
2020-05-01 19:10:17 +02:00
if (error.response?.status === 404) {
return true;
} else {
ApiService.handleError(error);
2020-05-01 19:10:17 +02:00
}
}
}
2021-04-25 12:05:17 +02:00
////////////
// UPDATE //
public async sendUpdateVoteStack(vote_stack: Stack) {
try {
2021-06-07 11:30:10 +02:00
return await this.axiosInstance.patch(
2021-06-07 12:16:56 +02:00
`${this.baseHref}/vote-stack/${vote_stack.id}/token/${vote_stack.owner.modifier_token}`,
2021-06-07 11:30:10 +02:00
vote_stack
);
} catch (error) {
ApiService.handleError(error);
}
}
public findMyPollsByEmail(email: string): Promise<any> {
return this.axiosInstance.get<any>(`${this.baseHref}/poll/owner/${email}`);
}
2020-06-12 19:17:39 +02:00
public async updateAnswer(slug: string, choiceLabel: string, pseudo: string, answer: Answer): Promise<string> {
try {
return await this.axiosInstance.patch(`${this.baseHref}/${slug}${this.answersEndpoint}`, {
2020-05-12 19:16:23 +02:00
choiceLabel,
pseudo,
2020-06-12 19:17:39 +02:00
answer,
2020-05-01 19:10:17 +02:00
});
} catch (error) {
ApiService.handleError(error);
}
}
////////////
// DELETE //
////////////
////////////
2020-05-12 19:16:23 +02:00
public async deletePoll(slug: string): Promise<boolean> {
try {
2020-05-12 19:16:23 +02:00
const response: AxiosResponse = await this.axiosInstance.delete(`${this.pollsEndpoint}/${slug}`);
return response?.status === 204;
} catch (error) {
ApiService.handleError(error);
}
}
2020-05-12 19:16:23 +02:00
public async deletePollAnswers(slug: string): Promise<boolean> {
try {
2020-05-12 19:16:23 +02:00
const response: AxiosResponse = await this.axiosInstance.delete(
`${this.pollsEndpoint}/${slug}${this.answersEndpoint}`
);
return response?.status === 204;
} catch (error) {
ApiService.handleError(error);
}
}
2020-05-12 19:16:23 +02:00
public async deletePollComments(slug: string): Promise<boolean> {
try {
2020-05-12 19:16:23 +02:00
const response: AxiosResponse = await this.axiosInstance.delete(
`${this.pollsEndpoint}/${slug}${this.commentsEndpoint}`
);
return response?.status === 204;
} catch (error) {
ApiService.handleError(error);
}
}
2021-05-20 14:49:37 +02:00
/////////////////////
// PRIVATE METHODS //
/////////////////////
2021-06-07 11:30:10 +02:00
private static handleError(error): void {
// this.loaderService.setStatus(true);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('Error response data', error.response.data);
console.error('Error response status', error.response.status);
console.error('Error response headers', error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log('ErrorRequest', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
// this.loaderService.setStatus(false);
}
2021-06-07 12:36:49 +02:00
public ousideHandleError(error) {
// this.loaderService.setStatus(true);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('Error response data', error.response.data);
console.error('Error response status', error.response.status);
console.error('Error response headers', error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log('ErrorRequest', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
// this.loaderService.setStatus(false);
}
}