From 5d70a737737d63c0767e6db95e14f0a00834ac39 Mon Sep 17 00:00:00 2001 From: Ricardo Hernandez-Montoya Date: Fri, 28 Apr 2017 11:43:15 +0200 Subject: [PATCH] issues #42 and #43 --- src/api/rest-api.js | 37 +++++++++++++++++++++++++++++++++++-- src/stores/user-store.js | 18 ++++++++++++------ 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/src/api/rest-api.js b/src/api/rest-api.js index 66e8211..6a79598 100644 --- a/src/api/rest-api.js +++ b/src/api/rest-api.js @@ -21,6 +21,36 @@ import request from 'superagent/lib/client'; import Promise from 'es6-promise'; +import NotificationsDataManager from '../data-managers/notifications-data-manager'; + + +// TODO: Add this to a central pool of notifications +const SERVER_NOT_REACHABLE_NOTIFICATION = { + title: 'Server not reachable', + message: 'The server could not be reached. Please try again later.', + level: 'error' + }; + +const REQUEST_TIMEOUT_NOTIFICATION = { + title: 'Request timeout', + message: 'Request timed out. Please try again later.', + level: 'error' + }; + +// Check if the error was due to network failure, timeouts, etc. +// Can be used for the rest of requests +function isNetworkError(err) { + let result = false; + + // If not status nor response fields, it is a network error. TODO: Handle timeouts + if (err.status == null || err.response == null) { + result = true; + + let notification = err.timeout? REQUEST_TIMEOUT_NOTIFICATION : SERVER_NOT_REACHABLE_NOTIFICATION; + NotificationsDataManager.addNotification(notification); + } + return result; +} class RestAPI { get(url, token) { @@ -43,14 +73,17 @@ class RestAPI { post(url, body, token) { return new Promise(function (resolve, reject) { - var req = request.post(url).send(body); + var req = request.post(url).send(body).timeout({ response: 5000 }); // Simple response start timeout (3s) if (token != null) { req.set('x-access-token', token); } - + req.end(function (error, res) { if (res == null || res.status !== 200) { + + error.handled = isNetworkError(error); + reject(error); } else { resolve(JSON.parse(res.text)); diff --git a/src/stores/user-store.js b/src/stores/user-store.js index 37fc363..aeed56f 100644 --- a/src/stores/user-store.js +++ b/src/stores/user-store.js @@ -67,12 +67,18 @@ class UserStore extends ReduceStore { return Object.assign({}, state, { currentUser: null, token: null }); case 'users/login-error': - // server offline - NotificationsDataManager.addNotification({ - title: 'Server offline', - message: 'The server is offline. Please try again later.', - level: 'error' - }); + + if (action.error && !action.error.handled) { + // If it was an error and hasn't been handled, the credentials must have been wrong. + const WRONG_CREDENTIALS_NOTIFICATION = { + title: 'Incorrect credentials', + message: 'Please modify and try again.', + level: 'error' + } + NotificationsDataManager.addNotification(WRONG_CREDENTIALS_NOTIFICATION); + + } + return state; default: