[O] Optimize login http fetch

This commit is contained in:
Hykilpikonna
2019-09-07 14:42:22 -04:00
parent 1ca32b5ebd
commit 448e699cd3
2 changed files with 23 additions and 27 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
<template> <template>
<div id="app"> <div id="app">
<login v-if="showLogin" v-on:login:token="onLogin"></login> <login v-if="showLogin" v-on:login:token="onLogin" :http="http"></login>
<navigation :courses="courses" v-on:navigation:select="onNavigate"></navigation> <navigation :courses="courses" v-on:navigation:select="onNavigate"></navigation>
<div id="app-content"> <div id="app-content">
+22 -26
View File
@@ -1,5 +1,6 @@
import {Component, Vue} from 'vue-property-decorator'; import {Component, Prop, Vue} from 'vue-property-decorator';
import Constants from '@/constants'; import Constants from '@/constants';
import {HttpUtils} from '@/utils/http-utils';
/** /**
* This component handles user login, and obtains data from the server. * This component handles user login, and obtains data from the server.
@@ -15,6 +16,9 @@ export default class Login extends Vue
public loading: boolean = false; public loading: boolean = false;
public error: String = ''; public error: String = '';
@Prop()
public http?: HttpUtils;
/** /**
* This is called when the instance is created. * This is called when the instance is created.
*/ */
@@ -36,35 +40,27 @@ export default class Login extends Vue
// Make login button loading // Make login button loading
this.loading = true; this.loading = true;
// Fetch request TODO: Add username and password when the https server is ready. // Fetch request
fetch(`${Constants.API_URL}/login`, (<HttpUtils> this.http).post('/login', {username: this.username, password: this.password})
{method: 'POST', body: JSON.stringify({username: this.username, password: this.password})}) .then(response =>
.then(res =>
{ {
// Get response body text // Check success
res.text().then(text => if (response.success)
{ {
// Parse response // Save token to cookies
let response = JSON.parse(text); this.$cookies.set('va.token', response.data, '7d');
// Check success // Call custom event with token
if (response.success) this.$emit('login:token', response.data);
{ }
// Save token to cookies else
this.$cookies.set('va.token', response.data, '7d'); {
// Show error message
this.error = response.data;
// Call custom event with token // Allow the user to retry
this.$emit('login:token', response.data); this.loading = false;
} }
else
{
// Show error message
this.error = response.data;
// Allow the user to retry
this.loading = false;
}
})
}) })
.catch(err => .catch(err =>
{ {