0

In my durandal app I need to know if the user is logged in different places. So currently i'm doing a call to get the user state in every views that needs it.

Is possible to do something like this:

//login.js

define(function(require) {
 var http = require('durandal/http')
 var isLogged;

 function getLogin() {
 if (isLogged != undefined) return isLogged
 return http.get('/api/login').then(function(data) {
  isLogged = data.logged
  return isLogged
  })
 }

 return {
  getLogin: getLogin
}

//view.js
define(function(require) {
 var login = require('login')
 function vm() {
  var self = this;
  self.isLogged;
  self.activate = function() {
   self.isLogged = login.getLogin()
  }
 }
 return vm
})

The above doesn't work because in the view activate method I need to return a promise. How can I achieve that?

Pietro Coelho
  • 1,894
  • 1
  • 26
  • 34
  • This " var http = require('login')", can be dangerous, if the "login" was not defined before, you will get an error! I recommend this syntax: "require('plugin/router', 'login', function (router, login) { ... }" – Samuel Pinto Aug 29 '15 at 00:22
  • possible duplicate of [Global variables for a single web page application using Durandal](http://stackoverflow.com/questions/20984031/global-variables-for-a-single-web-page-application-using-durandal) – Brett Sep 09 '15 at 17:12

1 Answers1

0

You can use guardRouter function!

This will be triggered in all navigation.

// Shell main or other file that runs before any view!
// Define the router guard function!

 require('plugin/router', 'Q', function(router, q){

     var cache = {};

     router.guardRoute = function(instance, instruction) {
         var key = instruction.fragment.toLowerCase();

         return cache[key] !== undefined ?
             cache[key]:
             q($.get(url,data)).then(_setCache, _fail);


         function _fail(/*jqhxr*/) {
            /* do something */
         }

         function _setCache(result) {
             cache[key] = result;
             return cache[key];
         }
     }

 });

If you return true, the navigation will proceed! in case of string returned, durandal will navigate into it!

The cache works as you define (check for javascript memoization)

About durandal Auth chech this gitHub for inspiration.

Samuel Pinto
  • 987
  • 11
  • 8
  • I think you didn't understand the question. I don't want to know how to redirect the user to another page if he isn't logged. I want to know how to create a module that can cache the result of calls - In the first call to the module method it does the API call, next time it only returns me the result of the previous call. – Pietro Coelho Aug 31 '15 at 18:37
  • I should added more information! I have written an example of router.guardRoute, because we can trigger a promise, and wait for resolution, before activating ANY view! About the cache, you can use the memoization such as in example (var cache = {};) – Samuel Pinto Sep 01 '15 at 23:16