]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+admin/users/user-edit/user-update.component.ts
Form validators refractoring
[github/Chocobozzz/PeerTube.git] / client / src / app / +admin / users / user-edit / user-update.component.ts
1 import { Component, OnDestroy, OnInit } from '@angular/core'
2 import { ActivatedRoute, Router } from '@angular/router'
3 import { Subscription } from 'rxjs'
4 import { NotificationsService } from 'angular2-notifications'
5 import { UserService } from '../shared'
6 import { User, USER_EMAIL, USER_ROLE, USER_VIDEO_QUOTA } from '../../../shared'
7 import { ServerService } from '../../../core'
8 import { UserEdit } from './user-edit'
9 import { UserUpdate } from '../../../../../../shared'
10 import { I18n } from '@ngx-translate/i18n-polyfill'
11 import { FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
12
13 @Component({
14 selector: 'my-user-update',
15 templateUrl: './user-edit.component.html',
16 styleUrls: [ './user-edit.component.scss' ]
17 })
18 export class UserUpdateComponent extends UserEdit implements OnInit, OnDestroy {
19 error: string
20 userId: number
21 username: string
22
23 private paramsSub: Subscription
24
25 constructor (
26 protected formValidatorService: FormValidatorService,
27 protected serverService: ServerService,
28 private route: ActivatedRoute,
29 private router: Router,
30 private notificationsService: NotificationsService,
31 private userService: UserService,
32 private i18n: I18n
33 ) {
34 super()
35 }
36
37 ngOnInit () {
38 const defaultValues = { videoQuota: '-1' }
39 this.buildForm({
40 email: USER_EMAIL,
41 role: USER_ROLE,
42 videoQuota: USER_VIDEO_QUOTA
43 }, defaultValues)
44
45 this.paramsSub = this.route.params.subscribe(routeParams => {
46 const userId = routeParams['id']
47 this.userService.getUser(userId).subscribe(
48 user => this.onUserFetched(user),
49
50 err => this.error = err.message
51 )
52 })
53 }
54
55 ngOnDestroy () {
56 this.paramsSub.unsubscribe()
57 }
58
59 formValidated () {
60 this.error = undefined
61
62 const userUpdate: UserUpdate = this.form.value
63
64 // A select in HTML is always mapped as a string, we convert it to number
65 userUpdate.videoQuota = parseInt(this.form.value['videoQuota'], 10)
66
67 this.userService.updateUser(this.userId, userUpdate).subscribe(
68 () => {
69 this.notificationsService.success(
70 this.i18n('Success'),
71 this.i18n('User {{username}} updated.', { username: this.username })
72 )
73 this.router.navigate([ '/admin/users/list' ])
74 },
75
76 err => this.error = err.message
77 )
78 }
79
80 isCreation () {
81 return false
82 }
83
84 getFormButtonTitle () {
85 return this.i18n('Update user')
86 }
87
88 private onUserFetched (userJson: User) {
89 this.userId = userJson.id
90 this.username = userJson.username
91
92 this.form.patchValue({
93 email: userJson.email,
94 role: userJson.role,
95 videoQuota: userJson.videoQuota
96 })
97 }
98 }