Durandal: how to cache calls? - javascript

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?

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.

Related

How to get utility function from helper file on node.js server?

I have a node/express server and I'm trying to get a function from a helper file to my app.js for use. Here is the function in the helper file:
CC.CURRENT.unpack = function(value)
{
var valuesArray = value.split("~");
var valuesArrayLenght = valuesArray.length;
var mask = valuesArray[valuesArrayLenght-1];
var maskInt = parseInt(mask,16);
var unpackedCurrent = {};
var currentField = 0;
for(var property in this.FIELDS)
{
if(this.FIELDS[property] === 0)
{
unpackedCurrent[property] = valuesArray[currentField];
currentField++;
}
else if(maskInt&this.FIELDS[property])
{
//i know this is a hack, for cccagg, future code please don't hate me:(, i did this to avoid
//subscribing to trades as well in order to show the last market
if(property === 'LASTMARKET'){
unpackedCurrent[property] = valuesArray[currentField];
}else{
unpackedCurrent[property] = parseFloat(valuesArray[currentField]);
}
currentField++;
}
}
return unpackedCurrent;
};
At the bottom of that helper file I did a module.export (The helper file is 400 lines long and I don't want to export every function in it):
module.exports = {
unpackMessage: function(value) {
CCC.CURRENT.unpack(value);
}
}
Then in my app.js I called
var helperUtil = require('./helpers/ccc-streamer-utilities.js');
and finally, I called that function in app.js and console.log it:
res = helperUtil.unpackMessage(message);
console.log(res);
The problem is that the console.log gives off an undefined every time, but in this example: https://github.com/cryptoqween/cryptoqween.github.io/tree/master/streamer/current (which is not node.js) it works perfectly. So I think I am importing wrong. All I want to do is use that utility function in my app.js
The unPackMessage(val) call doesn't return anything:
module.exports = {
unpackMessage: function(value) {
CCC.CURRENT.unpack(value);
}
}
you need to return CCC.CURRENT.UNPACK(value);
module.exports = {
unpackMessage: function(value) {
return CCC.CURRENT.unpack(value);
}
}

Node/commonJS can "private" variable leak between requests

In an imaginary Session module as bellow, could the _sessData variable be leaked in between request. For instance maybe a user just logged in, and at a "same time" a isAuthed() called is made for a different user. Could this be a problem? This module would be called on every request so I guess it's safe but a confirmation would be great.
module.exports = function(app) {
var _sessData = null;
function Session() {
//
}
Session.prototype.set = function( payload ) {
Cookies.set('session', payload);
_sessData = payload;
}
Session.prototype.isAuthed = function() {
return _sessData && Object.keys(_sessData).length > 0;
}
Session.prototype.clear = function() {
Cookies.set('session', '');
_sessData = {};
}
Object.defineProperty(app.context, 'Session', {
// Not exaclty sure what is happening here with this and _ctx..
// Note: apprently ctx is bound to the middleware when call()ing
get: function() { return new Session(this); }
});
return function * (next) {
var token = Cookies.get('jwt');
if ( ! token ) {
_sessData = {};
return yield* next;
}
try {
_sessData = jwt.verify(token, SECRET);
} catch(e) {
if (e.name === 'TokenExpiredError') {
this.Session.clear();
}
}
yield* next;
}
}
EDIT:
The module get used in a KoaJS app like so (the above module does not produce a proper KoaJS middleware but this is beside the point):
var app = require('koa')();
// JWT session middleware
var session = require("./session")();
app.use(session);
app.listen(3080);
What you are exporting is a function, so _sessData does not actually exist when you import the module. It gets created when you call the function. Each time the function is called -- and it needs to be called once per request -- a new variable in that scope with the name _sessData is created. No, they cannot interfere with each other.

Set factory variable from state

I am using factories to get feed data for different categories in wordpress using the Rest-API and I am wondering if I am making a complete mess of it.
I have around 13 different categories that I am making just a basic call to that look like this:
.factory('Articles1', function ($http) {
var articles1 = [];
storageKey = "articles1";
function _getCache() {
var cache = localStorage.getItem(storageKey );
if (cache)
articles = angular.fromJson(cache);
}
return {
all: function () {
return $http.get("http://www.example.com/wp-json/posts?filter[category_name]=category1").then(function (response) {
articles1 = response.data;
console.log(response.data);
return articles1;
});
},
get: function (articleId) {
if (!articles1.length)
_getCache();
for (var i = 0; i < articles1.length; i++) {
if (parseInt(articles1[i].ID) === parseInt(article1Id)) {
return articles1[i];
}
}
return null;
}
}
})
there is a separate call for each of the 13 categories to get articles.
Is there a way to set the [category_name] to a variable, possibly the state name or something to that I can just make 1 call to wordpress and the url will rely on what state the user has chosen? I have been trying to learn angular and from what I have seen I am sure there must be a more elegant way of doing something like this?
Inject the Angular $location provider and you will have access to every part of your current URL (you can also use it to listen to the state changes). Then just build the URL to Wordpress dynamically:
.factory('Articles1', function ($http, $location) {
// ...
return {
all: function () {
var currentCategory = $location.path().split('/')[1]; // Assuming the category is part of the path and at the second place
var wpUrl = 'http://www.example.com/wp-json/posts?filter[category_name]=' + currentCategory;
return $http.get(wpUrl).then(function (response) { // ...

Backbone data logic inside view

I am not sure where to perform the action of preparing the data for the template of my view. Currently I have this piece of code.
getTemplateData: function () {
var inventoryStatus = selectedDevice.get("inventoryStatus"),
data = {},
statusName,
inventoryDate;
statusName = getConfigValue("pdp", "statusMap", inventoryStatus);
data.message = getConfigValue("pdp", "statusMessage", statusName);
data.className = "";
data.dataAttribute = null;
data.tooltipValue = null;
data.displayError = false;
var redirectCode = (allDevices.get("thirdPartyRedirectCode") !== null) ? allDevices.get("thirdPartyRedirectCode") : "";
if (redirectCode) {
if (redirectCode === 9999) {
data.buttonDisabled = false;
data.buttonText = "Design Yours";
} else if (redirectCode === 9998) {
data.buttonDisabled = true;
data.buttonText = "Design Yours";
}
return false;
}
switch(inventoryStatus) {
case 1001: //Out of Stock
data.buttonDisabled = true;
data.displayError = true;
break;
case 1002: //Pre Order
data.buttonDisabled = false;
break;
}
return data;
}
This getTemplateData() I call inside my render function of the view. This seems wrong by the looks of it and i am unsure where to place this code.
Should I create different getters in my model or should i leave them inside my main view. Please help.
From what I know the "correct" way of doing this is to put it in the model, and in the view have
getTemplateData: function () {
return this.model.getTemplateData();
}
EDIT
In case of multiple models for a view (which shouldn't happen, without getting into your decisions at the moment) you can have a getTemplateData for each, and call them with something like extend:
getTemplateData: function () {
var data = this.model1.getTemplateData();
data = $.extend(data, this.model2.getTemplateData());
return data;
}
BUT
What you really should do, IMHO, is give each it's own view, where one of them is smaller and intended to be included in the other. (i.e. bigView.$el.append(smallView.el))

Return local variable in one function to another

I'm building an offline HTML page using Angular and using ydn-db for offline storage.
I have a database service like so,
demoApp.SericeFactory.database = function database() {
var database = {
dataStore: null,
admins: [],
students: [],
errors: [],
getadmindata: function(username) {
self = null, that = this
database.dataStore.get('admins', username).done(function(record) {
that.self = record;
return record;
}).fail(function(e) {
console.log(e);
database.errors.push(e);
});
return self; //This does not change.
}
};
database.dataStore = new ydn.db.Storage('DemoApp');
angular.forEach(INITSTUDENTS, function(student) {
database.dataStore.put('students', student, student.matricno);
database.students.push(student);
});
angular.forEach(INITADMINS, function(admin) {
database.dataStore.put('admins', admin, admin.username);
database.admins.push(admin);
});
return database;
I also have a controller that attempts to use the database;
function AppCntl ($scope, database) {
var user = database.getadmindata('user'); //I get nothing here.
}
What I have tried,
I have tried making changing self to var self
I have tried splitting the function like so
rq = database.dataStore.get('admins', 'user');
rq.done(function(record), {
self = record;
alert(self.name) //Works.
});
alert(self) //Doesn't work.
I have gone through questions like this o StackOverflow but nothings seems to be working for me or maybe I have just been looking in the wrong place.
Database request are asynchronous and hence it executes later after end of execution of the codes.
So when the last alert execute, self is still undefined. Secound alert execute after db request completion and it is usual right design pattern.
EDIT:
I have success with following code:
// Database service
angular.module('myApp.services', [])
.factory('database', function() {
return new ydn.db.Storage('feature-matrix', schema);
}
});
// controller using database service
angular.module('myApp.controllers', [])
.controller('HomeCtrl', ['$scope', 'utils', 'database', function($scope, utils, db) {
var index_name = 'platform, browser';
var key_range = null;
var limit = 200;
var offset = 0;
var reverse = false;
var unique = true;
db.keys('ydn-db-meta', index_name, key_range, limit, offset, reverse, unique)
.then(function(keys) {
var req = db.values('ydn-db', keys);
req.then(function(json) {
$scope.results = utils.processResult(json);
$scope.$apply();
}, function(e) {
throw e;
}, this);
});
}])
Complete app is available at https://github.com/yathit/feature-matrix
Running demo app is here: http://dev.yathit.com/demo/feature-matrix/index.html

Categories

Resources