send form in dev mode, fill title demo

This commit is contained in:
tykayn 2021-04-25 12:05:17 +02:00 committed by Baptiste Lemoine
parent 74a928800e
commit 215178efa9
4 changed files with 88 additions and 87 deletions

View File

@ -9,7 +9,7 @@ export class Poll {
constructor(
public owner: User = new User(),
public slug: string = '',
public title: string = '',
public title: string = 'mon titre',
public description?: string,
public creatorPseudo?: string,
public creatorEmail?: string,

View File

@ -19,10 +19,10 @@ const apiEndpoints = environment.api.endpoints;
providedIn: 'root',
})
export class ApiService {
private static loader: LoaderService;
private useDevLocalServer = true;
private devLocalServerBaseHref = 'http://localhost:8000/';
private axiosInstance: AxiosInstance;
private readonly pollsEndpoint = apiEndpoints.polls.name;
private readonly answersEndpoint = apiEndpoints.polls.answers.name;
private readonly commentsEndpoint = apiEndpoints.polls.comments.name;
@ -30,7 +30,6 @@ export class ApiService {
private readonly usersEndpoint = apiEndpoints.users.name;
private readonly usersPollsEndpoint = apiEndpoints.users.polls.name;
private readonly usersPollsSendEmailEndpoint = apiEndpoints.users.polls.sendEmail.name;
private static loader: LoaderService;
constructor(private http: HttpClient, private loader: LoaderService, private toastService: ToastService) {
this.axiosInstance = axios.create({ baseURL: apiBaseHref });
@ -46,37 +45,72 @@ export class ApiService {
// CREATE OR UPDATE //
//////////////////////
/////////////////////
/**
* 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',
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Accept,Accept-Language,Content-Language,Content-Type',
'Access-Control-Allow-Origin': '*',
};
const requestOptions = {
headers: new HttpHeaders(headerDict),
body: bodyContent,
};
return requestOptions;
}
private static handleError(error): void {
// this.loader.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.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);
}
public async createPoll(poll: Poll): Promise<Subscription> {
// this.loader.setStatus(true);
console.log('createPoll config', poll);
// const baseHref = this.useDevLocalServer ? 'http://localhost:8000' : apiBaseHref;
// return this.http
// .post(`${baseHref}${currentApiRoutes['api_new_poll']}`, poll, ApiService.makeHeaders())
// .subscribe(
// (res: Observable<any>) => {
// // redirect to the page to administrate the new poll
// this.toastService.display('Sondage Créé');
//
// console.log('res', res);
// // this.updateCurrentPollFromResponse(res);
//
// this.loader.setStatus(false);
// },
// (e) => {
// ApiService.handleError(e);
// }
// );
const baseHref = this.useDevLocalServer ? 'http://localhost:8000' : apiBaseHref;
return this.axiosInstance.post(
`${baseHref}${currentApiRoutes['api_new_poll']}`,
poll,
ApiService.makeHeaders()
);
try {
console.log('currentApiRoutes', currentApiRoutes);
return await this.axiosInstance.post(`${apiBaseHref}${currentApiRoutes['api_new_poll']}`, {
data: poll,
});
} catch (error) {
ApiService.handleError(error);
}
// try {
// console.log('currentApiRoutes', currentApiRoutes);
// return await this.axiosInstance.post(`${apiBaseHref}${currentApiRoutes['api_new_poll']}`, {
// data: poll,
// });
// } catch (error) {
// ApiService.handleError(error);
// }
}
//////////
// READ //
public async createParticipation(
pollId: string,
choiceLabel: string,
@ -102,8 +136,6 @@ export class ApiService {
}
}
//////////
// READ //
//////////
public async getAllAvailablePolls(): Promise<Poll[]> {
// TODO: used for facilities in DEV, should be removed in production
@ -183,6 +215,9 @@ export class ApiService {
}
}
////////////
// UPDATE //
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 {
@ -194,6 +229,9 @@ export class ApiService {
}
}
////////////
// DELETE //
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.
@ -208,8 +246,6 @@ export class ApiService {
}
}
////////////
// UPDATE //
////////////
public async updateAnswer(slug: string, choiceLabel: string, pseudo: string, answer: Answer): Promise<string> {
try {
@ -223,8 +259,6 @@ export class ApiService {
}
}
////////////
// DELETE //
////////////
public async deletePoll(slug: string): Promise<boolean> {
try {
@ -235,6 +269,9 @@ export class ApiService {
}
}
/////////////////////
// PRIVATE METHODS //
public async deletePollAnswers(slug: string): Promise<boolean> {
try {
const response: AxiosResponse = await this.axiosInstance.delete(
@ -256,49 +293,4 @@ export class ApiService {
ApiService.handleError(error);
}
}
/////////////////////
// PRIVATE METHODS //
/////////////////////
/**
* 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',
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Accept,Accept-Language,Content-Language,Content-Type',
'Access-Control-Allow-Origin': '*',
};
const requestOptions = {
headers: new HttpHeaders(headerDict),
body: bodyContent,
};
return requestOptions;
}
private static handleError(error): void {
// this.loader.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.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);
}
}

View File

@ -1,4 +1,4 @@
import { ChangeDetectorRef, Component, Inject, Input, OnInit } from '@angular/core';
import { ChangeDetectorRef, Component, Inject, Input } from '@angular/core';
import { ToastService } from '../../../../core/services/toast.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { UuidService } from '../../../../core/services/uuid.service';
@ -7,6 +7,7 @@ import { ApiService } from '../../../../core/services/api.service';
import { Router } from '@angular/router';
import { DOCUMENT } from '@angular/common';
import { Poll } from '../../../../core/models/poll.model';
import { environment } from '../../../../../environments/environment';
@Component({
selector: 'app-base-config',
@ -41,17 +42,25 @@ export class BaseConfigComponent {
console.log('newpoll', newpoll);
const router = this.router;
if (this.form.valid) {
console.log('Le sondage est correctement rempli, prêt à enregistrer.');
const newpoll = this.pollService.newPollFromForm(this.form);
// TODO : save the poll
if (!environment.production) {
this.toastService.display('mode dev : envoi du form sans validation');
this.apiService.createPoll(newpoll).then((resp) => {
console.log('resp', resp);
router.navigate(['success']);
});
} else {
this.toastService.display('invalid form');
if (this.form.valid) {
console.log('Le sondage est correctement rempli, prêt à enregistrer.');
const newpoll = this.pollService.newPollFromForm(this.form);
// TODO : save the poll
this.apiService.createPoll(newpoll).then((resp) => {
console.log('resp', resp);
router.navigate(['success']);
});
} else {
this.toastService.display('invalid form');
}
}
}

View File

@ -105,7 +105,7 @@ export class FormComponent implements OnInit {
*/
setDemoValues(): void {
this.form.patchValue({
title: '',
title: 'le titre de démo oh oh',
description: 'répondez SVP <3 ! *-* ',
slug: this.uuidService.getUUID(),
creatorPseudo: 'Chuck Norris',