From 215178efa9c6a3bc5e07d11b97dd0109ab356899 Mon Sep 17 00:00:00 2001 From: tykayn Date: Sun, 25 Apr 2021 12:05:17 +0200 Subject: [PATCH] send form in dev mode, fill title demo --- src/app/core/models/poll.model.ts | 2 +- src/app/core/services/api.service.ts | 148 +++++++++--------- .../form/base-config/base-config.component.ts | 23 ++- .../administration/form/form.component.ts | 2 +- 4 files changed, 88 insertions(+), 87 deletions(-) diff --git a/src/app/core/models/poll.model.ts b/src/app/core/models/poll.model.ts index e1bf0a6d..4c6d64fa 100644 --- a/src/app/core/models/poll.model.ts +++ b/src/app/core/models/poll.model.ts @@ -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, diff --git a/src/app/core/services/api.service.ts b/src/app/core/services/api.service.ts index 0e420acf..4ce80383 100644 --- a/src/app/core/services/api.service.ts +++ b/src/app/core/services/api.service.ts @@ -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 { // 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) => { - // // 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 { // 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 { // 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 { // 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 { try { @@ -223,8 +259,6 @@ export class ApiService { } } - //////////// - // DELETE // //////////// public async deletePoll(slug: string): Promise { try { @@ -235,6 +269,9 @@ export class ApiService { } } + ///////////////////// + // PRIVATE METHODS // + public async deletePollAnswers(slug: string): Promise { 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); - } } diff --git a/src/app/features/administration/form/base-config/base-config.component.ts b/src/app/features/administration/form/base-config/base-config.component.ts index 2a27d8e1..8d0b4d7b 100644 --- a/src/app/features/administration/form/base-config/base-config.component.ts +++ b/src/app/features/administration/form/base-config/base-config.component.ts @@ -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'); + } } } diff --git a/src/app/features/administration/form/form.component.ts b/src/app/features/administration/form/form.component.ts index aae22552..5e29d004 100644 --- a/src/app/features/administration/form/form.component.ts +++ b/src/app/features/administration/form/form.component.ts @@ -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',