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

223 lines
6.9 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';
@Injectable({
providedIn: 'root',
})
export class ApiService {
2020-05-01 19:10:17 +02:00
private axiosInstance: AxiosInstance;
2020-05-12 19:16:23 +02:00
2020-05-01 19:10:17 +02:00
private readonly pollsEndpoint = environment.api.endpoints.polls.name;
2020-05-12 19:16:23 +02:00
private readonly answersEndpoint = environment.api.endpoints.polls.answers.name;
2020-05-01 19:10:17 +02:00
private readonly commentsEndpoint = environment.api.endpoints.polls.comments.name;
private readonly slugsEndpoint = environment.api.endpoints.polls.slugs.name;
private readonly usersEndpoint = environment.api.endpoints.users.name;
private readonly usersPollsEndpoint = environment.api.endpoints.users.polls.name;
private readonly usersPollsSendEmailEndpoint = environment.api.endpoints.users.polls.sendEmail.name;
constructor() {
this.axiosInstance = axios.create({ baseURL: environment.api.baseHref });
2020-05-12 19:16:23 +02:00
this.axiosInstance.defaults.timeout = 2500;
this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/json';
2020-05-01 19:10:17 +02:00
}
2020-05-12 19:16:23 +02:00
//////////////////////
// CREATE OR UPDATE //
//////////////////////
public async createPoll(poll: Poll): Promise<string> {
try {
2020-05-12 19:16:23 +02:00
return await this.axiosInstance.post(`${this.pollsEndpoint}`, poll);
} catch (error) {
this.handleError(error);
}
}
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) {
this.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) {
this.handleError(error);
}
}
//////////
// READ //
//////////
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) {
this.handleError(error);
}
}
public async getPollBySlug(slug: string): Promise<Poll | undefined> {
// TODO: identifier should be decided according to backend : Id || Slug ?
try {
// TODO: this interceptor should be avoided if backends returns the good object
const adapterInterceptor: number = this.axiosInstance.interceptors.response.use(
2020-06-25 22:42:26 +02:00
(response: AxiosResponse): AxiosResponse => {
2020-05-12 19:16:23 +02:00
if (response.data['poll']) {
// response from cipherbliss backend, actually used by oldstuffModule
response.data = response.data['poll'];
} else if (response.data[0] && response.data[0]['slug'] && response.data[0]['question']) {
// response from local json-server
response.data = Poll.adaptFromLocalJsonServer(response.data[0]);
}
return response;
}
);
2020-06-18 16:15:26 +02:00
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
console.log('fetch API : asking for poll with slug=' + slug, { response });
2020-05-12 19:16:23 +02:00
axios.interceptors.request.eject(adapterInterceptor);
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 {
this.handleError(error);
}
}
}
public async getSlug(slug: string): Promise<boolean> {
try {
// TODO: scenario should be : if we can get this slug, 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 {
this.handleError(error);
}
}
}
2020-05-12 19:16:23 +02:00
public async sendEmailToUserOfItsPollsList(email: string): Promise<void> {
// If user is not authenticated: the list of polls is send to user's email by the backend.
try {
2020-05-01 19:10:17 +02:00
await this.axiosInstance.get<Poll[]>(
2020-05-12 19:16:23 +02:00
`${this.usersEndpoint}/${email}${this.usersPollsEndpoint}${this.usersPollsSendEmailEndpoint}`
);
} catch (error) {
this.handleError(error);
}
}
2020-05-12 19:16:23 +02:00
public async getPollsUrlsByUserEmail(email: string): Promise<Poll[]> {
// If user is authenticated : retrieve polls & display directly in frontend.
// TODO: Backend should handle this case. Actually the endpoint doesn't exist in backend.
2020-05-12 19:16:23 +02:00
// Here, only the list of slugs is usefull. Maybe just handle the list of slugs.
try {
2020-05-01 19:10:17 +02:00
const response: AxiosResponse<Poll[]> = await this.axiosInstance.get<Poll[]>(
2020-05-12 19:16:23 +02:00
`${this.usersEndpoint}/${email}${this.usersPollsEndpoint}`
);
2020-05-01 19:10:17 +02:00
return response?.data;
} catch (error) {
this.handleError(error);
}
}
////////////
// UPDATE //
////////////
2020-06-12 19:17:39 +02:00
public async updateAnswer(slug: string, choiceLabel: string, pseudo: string, answer: Answer): Promise<string> {
try {
2020-05-12 19:16:23 +02:00
return await this.axiosInstance.patch(`${this.pollsEndpoint}/${slug}${this.answersEndpoint}`, {
choiceLabel,
pseudo,
2020-06-12 19:17:39 +02:00
answer,
2020-05-01 19:10:17 +02:00
});
} catch (error) {
this.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) {
this.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) {
this.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) {
this.handleError(error);
}
}
/////////////////////
// PRIVATE METHODS //
/////////////////////
private handleError(error): void {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(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(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
}
}