reuse automatic slug from poll config in form

This commit is contained in:
tykayn 2020-11-09 11:32:12 +01:00
parent 04f04d622d
commit 3306e7c29d
8 changed files with 133 additions and 50 deletions

View File

@ -1,32 +1,41 @@
// TODO: File to be deleted : just temporary documentation of backend API endpoints // TODO: File to be deleted : just temporary documentation of backend API endpoints
/** ------------------------------------------ ---------- -------- ------ ------------------------------------------------
*
* -------------------------- -------- -------- ------ ------------------------------------------------
Name Method Scheme Host Path Name Method Scheme Host Path
-------------------------- -------- -------- ------ ------------------------------------------------ ------------------------------------------ ---------- -------- ------ ------------------------------------------------
_twig_error_test ANY ANY ANY /_error/{code}.{_format} _twig_error_test ANY ANY ANY /_error/{code}.{_format}
admin_homepage_get_default GET ANY ANY /admin/ admin_homepage_get_default GET ANY ANY /admin/
admin_homepage_clean_expired_polls GET ANY ANY /admin/polls/clean/{token} admin_homepage_clean_expired_polls GET ANY ANY /admin/polls/clean/{token}
api_get_poll_comment GET ANY ANY /polls/{id}/comments admin_homepage_migrate_framadate GET ANY ANY /admin/polls/migrate
api_new_comment POST ANY ANY /polls/{id}/comments api_get_poll_comment GET ANY ANY /api/v1/poll/{id}/comments
api_poll_comments_delete DELETE ANY ANY /polls/{id}/comments api_new_comment POST ANY ANY /api/v1/poll/{id}/comment
user_homepageget_default GET ANY ANY /users/ api_poll_comments_delete DELETE ANY ANY /api/v1/poll/{id}/comments
user_homepage_polls_send_by_email GET ANY ANY /users/{email}/polls/send-by-email api_page_home GET ANY ANY /page/
api_get_all_polls GET ANY ANY /polls/ user_homepageget_default GET ANY ANY /user/
api_get_poll GET ANY ANY /polls/{id} user_homepage_polls_send_by_email GET ANY ANY /user/{email}/polls/send-by-email
api_update_poll PUT ANY ANY /polls/{id}/{token} poll_index GET ANY ANY /poll/
api_new_poll POST ANY ANY /polls/ poll_new GET|POST ANY ANY /poll/new
api_test-mail-polls GET ANY ANY /polls/mail/test-mail-polls/{emailChoice} poll_show GET ANY ANY /poll/{id}
api_poll_delete DELETE ANY ANY /polls/{id} poll_edit GET|POST ANY ANY /poll/{id}/edit
api_check_slug_is_unique GET ANY ANY /polls/slugs/{slug} poll_delete DELETE ANY ANY /poll/{id}
api_get_admin_config GET ANY ANY /polls/admin/{token} api_new_vote_stack POST ANY ANY /api/v1/poll/{id}/answer
api_new_vote_stack POST ANY ANY /polls/{id}/votes api_update_vote_stack PATCH ANY ANY /api/v1/vote-stack/{id}/token/{modifierToken}
api_update_vote_stack PATCH ANY ANY /votes-stacks/{id}/token/{modifierToken} api_poll_votes_delete DELETE ANY ANY /api/v1/poll/{id}/votes/{accessToken}
api_poll_votes_delete DELETE ANY ANY /polls/{id}/votes/{accessToken} api_get_all_polls GET ANY ANY /api/v1/poll/
api_get_poll GET ANY ANY /api/v1/poll/{id}
api_update_poll PUT ANY ANY /api/v1/poll/{id}/{token}
api_new_poll POST ANY ANY /api/v1/poll/
api_test-mail-poll GET ANY ANY /api/v1/poll/mail/test-mail-poll/{emailChoice}
api_poll_delete DELETE ANY ANY /api/v1/poll/{id}
api_check_slug_is_unique GET ANY ANY /api/v1/poll/slug/{slug}
api_get_admin_config GET ANY ANY /api/v1/poll/admin/{token}
overblog_graphql_endpoint ANY ANY ANY /api/graphql/
overblog_graphql_batch_endpoint ANY ANY ANY /api/graphql/batch
overblog_graphql_multiple_endpoint ANY ANY ANY /api/graphql/graphql/{schemaName}
overblog_graphql_batch_multiple_endpoint ANY ANY ANY /api/graphql/graphql/{schemaName}/batch
app.swagger GET ANY ANY /api/doc.json app.swagger GET ANY ANY /api/doc.json
-------------------------- -------- -------- ------ ------------------------------------------------ ------------------------------------------ ---------- -------- ------ ------------------------------------------------
*/
/** /**
* WANTED CHANGES (seraf) * WANTED CHANGES (seraf)

View File

@ -4,6 +4,7 @@ import { environment } from 'src/environments/environment';
import { Answer } from '../enums/answer.enum'; import { Answer } from '../enums/answer.enum';
import { Poll } from '../models/poll.model'; import { Poll } from '../models/poll.model';
import { HttpHeaders } from '@angular/common/http';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@ -32,7 +33,7 @@ export class ApiService {
try { try {
return await this.axiosInstance.post(`${this.pollsEndpoint}`, poll); return await this.axiosInstance.post(`${this.pollsEndpoint}`, poll);
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -49,7 +50,7 @@ export class ApiService {
response, response,
}); });
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -57,7 +58,7 @@ export class ApiService {
try { try {
return await this.axiosInstance.post(`${this.pollsEndpoint}/${slug}${this.commentsEndpoint}`, comment); return await this.axiosInstance.post(`${this.pollsEndpoint}/${slug}${this.commentsEndpoint}`, comment);
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -70,7 +71,7 @@ export class ApiService {
const response: AxiosResponse<Poll[]> = await this.axiosInstance.get<Poll[]>(`${this.pollsEndpoint}`); const response: AxiosResponse<Poll[]> = await this.axiosInstance.get<Poll[]>(`${this.pollsEndpoint}`);
return response?.data; return response?.data;
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -101,7 +102,7 @@ export class ApiService {
if (error.response?.status === 404) { if (error.response?.status === 404) {
return undefined; return undefined;
} else { } else {
this.handleError(error); ApiService.handleError(error);
} }
} }
} }
@ -119,7 +120,7 @@ export class ApiService {
if (error.response?.status === 404) { if (error.response?.status === 404) {
return true; return true;
} else { } else {
this.handleError(error); ApiService.handleError(error);
} }
} }
} }
@ -131,7 +132,7 @@ export class ApiService {
`${this.usersEndpoint}/${email}${this.usersPollsEndpoint}${this.usersPollsSendEmailEndpoint}` `${this.usersEndpoint}/${email}${this.usersPollsEndpoint}${this.usersPollsSendEmailEndpoint}`
); );
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -145,7 +146,7 @@ export class ApiService {
); );
return response?.data; return response?.data;
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -160,7 +161,7 @@ export class ApiService {
answer, answer,
}); });
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -172,7 +173,7 @@ export class ApiService {
const response: AxiosResponse = await this.axiosInstance.delete(`${this.pollsEndpoint}/${slug}`); const response: AxiosResponse = await this.axiosInstance.delete(`${this.pollsEndpoint}/${slug}`);
return response?.status === 204; return response?.status === 204;
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -183,7 +184,7 @@ export class ApiService {
); );
return response?.status === 204; return response?.status === 204;
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
@ -194,14 +195,35 @@ export class ApiService {
); );
return response?.status === 204; return response?.status === 204;
} catch (error) { } catch (error) {
this.handleError(error); ApiService.handleError(error);
} }
} }
///////////////////// /////////////////////
// PRIVATE METHODS // // PRIVATE METHODS //
///////////////////// /////////////////////
private handleError(error): void { /**
* prepare headers like the charset and json type for any call to the backend
* @param bodyContent?
*/
private 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-Origin': '*',
};
const requestOptions = {
headers: new HttpHeaders(headerDict),
body: bodyContent,
};
return requestOptions;
}
private static handleError(error): void {
if (error.response) { if (error.response) {
// The request was made and the server responded with a status code // The request was made and the server responded with a status code
// that falls out of the range of 2xx // that falls out of the range of 2xx

View File

@ -11,6 +11,7 @@ import { ToastService } from './toast.service';
import { UserService } from './user.service'; import { UserService } from './user.service';
import { UuidService } from './uuid.service'; import { UuidService } from './uuid.service';
import { Form } from '@angular/forms'; import { Form } from '@angular/forms';
import { PollConfig } from '../../features/old-stuff/config/PollConfig';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@ -60,6 +61,40 @@ export class PollService implements Resolve<Poll> {
this._poll.next(poll); this._poll.next(poll);
} }
/**
* make a uniq slug for the current poll creation
* @param config
*/
makeSlug(config: Poll): string {
let str = '';
str =
config.configuration.dateCreated.getFullYear() +
'_' +
(config.configuration.dateCreated.getMonth() + 1) +
'_' +
config.configuration.dateCreated.getDate() +
'_' +
config.owner.pseudo +
'_' +
config.title;
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
const from = 'àáäâèéëêìíïîòóöôùúüûñç·/_,:;';
const to = 'aaaaeeeeiiiioooouuuunc------';
for (let i = 0, l = from.length; i < l; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str
.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str + '-' + this.uuidService.getUUID();
}
public async saveCurrentPoll(): Promise<void> { public async saveCurrentPoll(): Promise<void> {
const pollUrl: string = await this.apiService.createPoll(this._poll.getValue()); const pollUrl: string = await this.apiService.createPoll(this._poll.getValue());
// TODO: Maybe handle the url to update currentPoll according to backend response // TODO: Maybe handle the url to update currentPoll according to backend response

View File

@ -10,4 +10,14 @@ export class UuidService {
public getUUID(): string { public getUUID(): string {
return this.uid(); return this.uid();
} }
/**
* generate unique id to have a default url for future poll
*/
getLongUUID(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
} }

View File

@ -1,10 +1,4 @@
<!--<div class="columns">--> <div class="columns administration">
<!-- <div class="column has-text-centered">-->
<!-- <h1>Administration</h1>-->
<!-- </div>-->
<!--</div>-->
<div class="columns">
<div class="column"> <div class="column">
<app-admin-form [poll]="poll"></app-admin-form> <app-admin-form [poll]="poll"></app-admin-form>
</div> </div>

View File

@ -5,7 +5,6 @@ import { Subscription } from 'rxjs';
import { Poll } from '../../core/models/poll.model'; import { Poll } from '../../core/models/poll.model';
import { ModalService } from '../../core/services/modal.service'; import { ModalService } from '../../core/services/modal.service';
import { UserService } from '../../core/services/user.service'; import { UserService } from '../../core/services/user.service';
import { SettingsComponent } from '../../shared/components/settings/settings.component';
@Component({ @Component({
selector: 'app-administration', selector: 'app-administration',
@ -13,8 +12,7 @@ import { SettingsComponent } from '../../shared/components/settings/settings.com
styleUrls: ['./administration.component.scss'], styleUrls: ['./administration.component.scss'],
}) })
export class AdministrationComponent implements OnInit, OnDestroy { export class AdministrationComponent implements OnInit, OnDestroy {
public poll: Poll; public poll: Poll = new Poll();
public form: Object;
private routeSubscription: Subscription; private routeSubscription: Subscription;
constructor(private route: ActivatedRoute, private userService: UserService, private modalService: ModalService) {} constructor(private route: ActivatedRoute, private userService: UserService, private modalService: ModalService) {}

View File

@ -12,6 +12,14 @@
<i class="fa fa-save"></i> <i class="fa fa-save"></i>
Enregistrer le sondage Enregistrer le sondage
</button> </button>
<button class="btn is-default" (click)="automaticSlug()">
<i class="fa fa-save"></i>
Slug automatique
</button>
<div class="well">
{{ poll.slug }}
</div>
<div class="bg-danger" *ngIf="!form.valid"> <div class="bg-danger" *ngIf="!form.valid">
le formulaire est invalide le formulaire est invalide
</div> </div>

View File

@ -306,4 +306,11 @@ export class FormComponent implements OnInit {
elem.focus(); elem.focus();
} }
} }
/**
* set the poll slug from other data of the poll
*/
automaticSlug() {
this.poll.slug = this.pollService.makeSlug(this.poll);
}
} }