Skip to content

Instantly share code, notes, and snippets.

@gr2m
Created May 28, 2014 17:55
Show Gist options
  • Save gr2m/116357aedf3ca8a1a621 to your computer and use it in GitHub Desktop.
Save gr2m/116357aedf3ca8a1a621 to your computer and use it in GitHub Desktop.
Hoodie Plugin that maintains a local list of user accounts that have been used in a browser. See discussion at https://github.com/hoodiehq/discussion/issues/42
'use strict';
var hoodie = require('backbone').hoodie;
hoodie.extend(function(hoodie,lib, utils) {
var PROFILES_STORE_KEY = '_hoodie_profiles';
var store = utils.localStorageWrapper;
var api = getAllProfiles;
var profiles = store.getObject(PROFILES_STORE_KEY) || [];
//
// Initialization
//
hoodie.account.on('signin signup', handleAccountSignInOrSignUp);
//
// PUBLIC API
//
//
api.find = function find(username) {
for (var i = 0; i < profiles.length; i++) {
if (profiles[i].username === username) return profiles[i];
}
};
//
api.add = function add(username, properties) {
var existingProfile = api.find(username);
if (!properties) properties = {};
if (existingProfile) return api.update(username, properties);
properties.username = username;
profiles.push(properties);
persistChanges();
return true;
};
//
api.update = function update(username, changedProperties) {
var existingProfile = api.find(username);
if (! existingProfile) return false;
for (var property in changedProperties) {
if (changedProperties.hasOwnProperty(property)) {
existingProfile[property] = changedProperties[property];
}
}
persistChanges();
return true;
};
//
api.remove = function remove(username) {
var existingProfile = api.find(username);
if (! existingProfile) return false;
profiles.splice(existingProfile, 1);
persistChanges();
return true;
};
//
api.clear = function clear() {
profiles = [];
persistChanges();
return true;
};
//
api.lastActive = function lastActive() {
if (! profiles.length) return;
return profiles.sort( function(profile1, profile2) {
return profile1.lastActiveAt > profile2.lastActiveAt ? -1 : 1;
})[0];
};
//
// INTERNAL HELPERS
//
function getAllProfiles() {
return profiles;
}
function persistChanges () {
if (profiles.length) {
store.setObject(PROFILES_STORE_KEY, profiles);
return;
}
store.removeItem(PROFILES_STORE_KEY);
}
function handleAccountSignInOrSignUp (username) {
api.add(username, {lastActiveAt: new Date().toJSON()});
persistChanges();
}
hoodie.profiles = api;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment