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( constructor(
public owner: User = new User(), public owner: User = new User(),
public slug: string = '', public slug: string = '',
public title: string = '', public title: string = 'mon titre',
public description?: string, public description?: string,
public creatorPseudo?: string, public creatorPseudo?: string,
public creatorEmail?: string, public creatorEmail?: string,

View File

@ -19,10 +19,10 @@ const apiEndpoints = environment.api.endpoints;
providedIn: 'root', providedIn: 'root',
}) })
export class ApiService { export class ApiService {
private static loader: LoaderService;
private useDevLocalServer = true; private useDevLocalServer = true;
private devLocalServerBaseHref = 'http://localhost:8000/'; private devLocalServerBaseHref = 'http://localhost:8000/';
private axiosInstance: AxiosInstance; private axiosInstance: AxiosInstance;
private readonly pollsEndpoint = apiEndpoints.polls.name; private readonly pollsEndpoint = apiEndpoints.polls.name;
private readonly answersEndpoint = apiEndpoints.polls.answers.name; private readonly answersEndpoint = apiEndpoints.polls.answers.name;
private readonly commentsEndpoint = apiEndpoints.polls.comments.name; private readonly commentsEndpoint = apiEndpoints.polls.comments.name;
@ -30,7 +30,6 @@ export class ApiService {
private readonly usersEndpoint = apiEndpoints.users.name; private readonly usersEndpoint = apiEndpoints.users.name;
private readonly usersPollsEndpoint = apiEndpoints.users.polls.name; private readonly usersPollsEndpoint = apiEndpoints.users.polls.name;
private readonly usersPollsSendEmailEndpoint = apiEndpoints.users.polls.sendEmail.name; private readonly usersPollsSendEmailEndpoint = apiEndpoints.users.polls.sendEmail.name;
private static loader: LoaderService;
constructor(private http: HttpClient, private loader: LoaderService, private toastService: ToastService) { constructor(private http: HttpClient, private loader: LoaderService, private toastService: ToastService) {
this.axiosInstance = axios.create({ baseURL: apiBaseHref }); this.axiosInstance = axios.create({ baseURL: apiBaseHref });
@ -46,37 +45,72 @@ export class ApiService {
// CREATE OR UPDATE // // 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> { public async createPoll(poll: Poll): Promise<Subscription> {
// this.loader.setStatus(true); // this.loader.setStatus(true);
console.log('createPoll config', poll); console.log('createPoll config', poll);
// const baseHref = this.useDevLocalServer ? 'http://localhost:8000' : apiBaseHref; const baseHref = this.useDevLocalServer ? 'http://localhost:8000' : apiBaseHref;
// return this.http return this.axiosInstance.post(
// .post(`${baseHref}${currentApiRoutes['api_new_poll']}`, poll, ApiService.makeHeaders()) `${baseHref}${currentApiRoutes['api_new_poll']}`,
// .subscribe( poll,
// (res: Observable<any>) => { ApiService.makeHeaders()
// // 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);
// }
// );
try { // try {
console.log('currentApiRoutes', currentApiRoutes); // console.log('currentApiRoutes', currentApiRoutes);
return await this.axiosInstance.post(`${apiBaseHref}${currentApiRoutes['api_new_poll']}`, { // return await this.axiosInstance.post(`${apiBaseHref}${currentApiRoutes['api_new_poll']}`, {
data: poll, // data: poll,
}); // });
} catch (error) { // } catch (error) {
ApiService.handleError(error); // ApiService.handleError(error);
} // }
} }
//////////
// READ //
public async createParticipation( public async createParticipation(
pollId: string, pollId: string,
choiceLabel: string, choiceLabel: string,
@ -102,8 +136,6 @@ export class ApiService {
} }
} }
//////////
// READ //
////////// //////////
public async getAllAvailablePolls(): Promise<Poll[]> { public async getAllAvailablePolls(): Promise<Poll[]> {
// TODO: used for facilities in DEV, should be removed in production // 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> { 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. // If user is not authenticated: the list of polls is send to user's email by the backend.
try { try {
@ -194,6 +229,9 @@ export class ApiService {
} }
} }
////////////
// DELETE //
public async getPollsUrlsByUserEmail(email: string): Promise<Poll[]> { public async getPollsUrlsByUserEmail(email: string): Promise<Poll[]> {
// If user is authenticated : retrieve polls & display directly in frontend. // If user is authenticated : retrieve polls & display directly in frontend.
// TODO: Backend should handle this case. Actually the endpoint doesn't exist in backend. // 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> { public async updateAnswer(slug: string, choiceLabel: string, pseudo: string, answer: Answer): Promise<string> {
try { try {
@ -223,8 +259,6 @@ export class ApiService {
} }
} }
////////////
// DELETE //
//////////// ////////////
public async deletePoll(slug: string): Promise<boolean> { public async deletePoll(slug: string): Promise<boolean> {
try { try {
@ -235,6 +269,9 @@ export class ApiService {
} }
} }
/////////////////////
// PRIVATE METHODS //
public async deletePollAnswers(slug: string): Promise<boolean> { public async deletePollAnswers(slug: string): Promise<boolean> {
try { try {
const response: AxiosResponse = await this.axiosInstance.delete( const response: AxiosResponse = await this.axiosInstance.delete(
@ -256,49 +293,4 @@ export class ApiService {
ApiService.handleError(error); 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 { ToastService } from '../../../../core/services/toast.service';
import { FormBuilder, FormGroup } from '@angular/forms'; import { FormBuilder, FormGroup } from '@angular/forms';
import { UuidService } from '../../../../core/services/uuid.service'; import { UuidService } from '../../../../core/services/uuid.service';
@ -7,6 +7,7 @@ import { ApiService } from '../../../../core/services/api.service';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { DOCUMENT } from '@angular/common'; import { DOCUMENT } from '@angular/common';
import { Poll } from '../../../../core/models/poll.model'; import { Poll } from '../../../../core/models/poll.model';
import { environment } from '../../../../../environments/environment';
@Component({ @Component({
selector: 'app-base-config', selector: 'app-base-config',
@ -41,6 +42,13 @@ export class BaseConfigComponent {
console.log('newpoll', newpoll); console.log('newpoll', newpoll);
const router = this.router; const router = this.router;
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 {
if (this.form.valid) { if (this.form.valid) {
console.log('Le sondage est correctement rempli, prêt à enregistrer.'); console.log('Le sondage est correctement rempli, prêt à enregistrer.');
const newpoll = this.pollService.newPollFromForm(this.form); const newpoll = this.pollService.newPollFromForm(this.form);
@ -54,6 +62,7 @@ export class BaseConfigComponent {
this.toastService.display('invalid form'); this.toastService.display('invalid form');
} }
} }
}
public updateSlug(): void { public updateSlug(): void {
const newValueFormatted = 'TODO'; const newValueFormatted = 'TODO';

View File

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