Skip to content

Instantly share code, notes, and snippets.

@guibot17
Forked from katowulf/1_using_queries.js
Last active September 15, 2015 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guibot17/d60adaa488488fbda3b8 to your computer and use it in GitHub Desktop.
Save guibot17/d60adaa488488fbda3b8 to your computer and use it in GitHub Desktop.
Methods to search for user accounts by email address in Firebase
/***************************************************
* Assuming you can't use priorities (e.g. they are already being used for something else)
* You can store the email addresses in an index and use that to match them to user ids
***************************************************/
var fb = new Firebase(URL);
/**
* Looks up a user id by email address and invokes callback with the id or null if not found
* @return {Object|null} the object contains the key/value hash for one user
*/
function getUserIdByEmail( emailAddress, callback ) {
fb.child('emails_to_ids/'+emailToKey(emailAddress)).once('value', function(snap) {
callback( snap.val() );
});
}
/**
* Creates a new user record and also updates the index
*/
function createNewUser( userRecord ) {
var id = fb.child('user').push(userRecord).name();
fb.child('emails_to_ids/'+userRecord.email).set(id);
return id;
}
/**
* Firebase keys cannot have a period (.) in them, so this converts the emails to valid keys
*/
function emailToKey(emailAddress) {
return emailAddress.replace('.', ',');
}
/***************************************************
* You can set the priority on the user records to the email address, then use that to look them up.
* Assumes user records are stored in the /user path
***************************************************/
var fb = new Firebase(URL);
/**
* @param {string} emailAddress
* @return {Object} the object contains zero or more user records, the keys are the users' ids
*/
function findUsersMatchingEmail( emailAddress, callback ) {
fb.child('user').startAt(emailAddress).endAt(emailAddress).once('value', function(snap) {
// the keys are the user ids, the values are objects containing each user record that matched (presumably 1?)
callback( snap.val() || {} );
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment