From 447c1894d9b2449c6816e4b6dcb31ffe55164f95 Mon Sep 17 00:00:00 2001 From: William Brawner Date: Wed, 9 Nov 2022 01:48:30 +0000 Subject: [PATCH] Use promises for register and logout --- src/app/app.component.ts | 2 +- src/app/shared/twigs.http.service.ts | 87 ++++++++++++-------- src/app/shared/twigs.local.service.ts | 13 ++- src/app/shared/twigs.service.ts | 4 +- src/app/users/register/register.component.ts | 4 +- 5 files changed, 62 insertions(+), 48 deletions(-) diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 8ad4a71..2af3cd1 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -107,7 +107,7 @@ export class AppComponent implements OnInit { } logout(): void { - this.twigsService.logout().subscribe(_ => { + this.twigsService.logout().then(_ => { this.location.go('/'); window.location.reload(); }); diff --git a/src/app/shared/twigs.http.service.ts b/src/app/shared/twigs.http.service.ts index 35594a3..6ca3898 100644 --- a/src/app/shared/twigs.http.service.ts +++ b/src/app/shared/twigs.http.service.ts @@ -25,42 +25,32 @@ export class TwigsHttpService implements TwigsService { private storage: Storage ) { } - login(email: string, password: string): Promise { - return fetch(this.apiUrl + '/users/login', { - method: 'POST', - headers: { - 'content-type': 'application/json' - }, - body: JSON.stringify({ - 'username': email, - 'password': password - }) - }) - .then(res => res.json()) - .then((auth: AuthToken) => { - this.storage.setItem('Authorization', auth.token); - this.storage.setItem('userId', auth.userId); - return this.getProfile(auth.userId); - }); + async login(email: string, password: string): Promise { + const url = new URL('/api/users/login', this.apiUrl) + const auth: AuthToken = await this.request(url, HttpMethod.POST, { + 'username': email, + 'password': password + }); + this.storage.setItem('Authorization', auth.token); + this.storage.setItem('userId', auth.userId); + return await this.getProfile(auth.userId); } - register(username: string, email: string, password: string): Observable { - const params = { + register(username: string, email: string, password: string): Promise { + const body = { 'username': username, 'email': email, 'password': password }; - return this.http.post(this.apiUrl + '/users/register', params, this.options); + const url = new URL('/api/users/register', this.apiUrl) + return this.request(url, HttpMethod.POST, body); } - logout(): Observable { - return new Observable(emitter => { - this.storage.removeItem('Authorization'); - this.storage.removeItem('userId'); - emitter.next(); - emitter.complete(); - }) - // TODO: Implement this when JWT auth is implemented + logout(): Promise { + this.storage.removeItem('Authorization'); + this.storage.removeItem('userId'); + return Promise.resolve() + // TODO: Implement this to revoke the token server-side as well // return this.http.post(this.apiUrl + '/login?logout', this.options); } @@ -308,13 +298,8 @@ export class TwigsHttpService implements TwigsService { // Users getProfile(id: string): Promise { - return fetch(`${this.apiUrl}/users/${id}`, { - credentials: 'include', - headers: { - 'Authorization': `Bearer ${this.storage.getItem('Authorization')}` - } - }) - .then(res => res.json()); + const url = new URL(`/api/users/${id}`, this.apiUrl) + return this.request(url, HttpMethod.GET) } getUsersByUsername(username: string): Observable { @@ -322,4 +307,36 @@ export class TwigsHttpService implements TwigsService { subscriber.error("Not yet implemented") }); } + + private async request(url: URL, method: HttpMethod, body?: any): Promise { + const headers = { + 'content-type': 'application/json' + } + + const token = this.storage.getItem('Authorization') + if (token) { + headers['authorization'] = `Bearer ${token}` + } + + let jsonBody: string; + if (body) { + jsonBody = JSON.stringify(body) + } + + const res = await fetch(url, { + credentials: 'include', + headers: headers, + method: method, + body: jsonBody + }) + + return res.json() + } +} + +enum HttpMethod { + GET = "GET", + POST = "POST", + PUT = "PUT", + DELETE = "DELETE", } diff --git a/src/app/shared/twigs.local.service.ts b/src/app/shared/twigs.local.service.ts index 97148f2..276cc26 100644 --- a/src/app/shared/twigs.local.service.ts +++ b/src/app/shared/twigs.local.service.ts @@ -40,22 +40,19 @@ export class TwigsLocalService implements TwigsService { }); } - register(username: string, email: string, password: string): Observable { - return new Observable(subscriber => { + register(username: string, email: string, password: string): Promise { + return new Promise((resolve, reject) => { const user = new User(); user.username = username; user.email = email; user.id = randomId(); this.users.push(user); - subscriber.next(user); - subscriber.complete(); + resolve(user); }); } - logout(): Observable { - return new Observable(subscriber => { - subscriber.complete(); - }); + logout(): Promise { + return Promise.resolve() } // Budgets diff --git a/src/app/shared/twigs.service.ts b/src/app/shared/twigs.service.ts index ea6cb8b..554c5b8 100644 --- a/src/app/shared/twigs.service.ts +++ b/src/app/shared/twigs.service.ts @@ -8,8 +8,8 @@ import { Transaction } from '../transactions/transaction'; export interface TwigsService { // Auth login(email: string, password: string): Promise; - register(username: string, email: string, password: string): Observable; - logout(): Observable; + register(username: string, email: string, password: string): Promise; + logout(): Promise; // Budgets getBudgets(): Observable; diff --git a/src/app/users/register/register.component.ts b/src/app/users/register/register.component.ts index 4f2e231..7e984cd 100644 --- a/src/app/users/register/register.component.ts +++ b/src/app/users/register/register.component.ts @@ -33,10 +33,10 @@ export class RegisterComponent implements OnInit { return; } this.isLoading = true; - this.twigsService.register(this.username, this.email, this.password).subscribe(user => { + this.twigsService.register(this.username, this.email, this.password).then(user => { console.log(user); this.router.navigate(['/']) - }, error => { + }).catch(error => { console.error(error); alert("Registration failed!") this.isLoading = false;