-
Notifications
You must be signed in to change notification settings - Fork 3
/
firebaseHelper.js
87 lines (83 loc) · 2.59 KB
/
firebaseHelper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var firebase = require('firebase');
var values = require('./values');
var firebaseHelper = {
database: null,
init: function() {
var config = {
apiKey: values.firebaseAPIKey,
authDomain: values.firebaseAuthDomain,
databaseURL: values.firebaseDatabaseUrl
};
this.app = firebase.initializeApp(config);
firebase.auth().onAuthStateChanged( function( user ) {
if ( user ) {
console.log( "server signed in to firebase with account:", user.email );
} else {
console.log( "server signed out of firebase" );
}
});
firebase.auth().signInWithEmailAndPassword( values.userEmail, values.userPassword ).catch( function( err ) {
var errorCode = err.code;
var errorMessage = err.message;
console.error( "sign in to firebase failed, errorCode:%s, errorMessage:%s", errorCode, errorMessage );
});
this.database = firebase.database();
},
getQuizzesRef: function( callback ) {
var quizzesRef = this.database.ref( 'quizzes' );
callback( quizzesRef );
},
createQuiz: function( quiz ) {
this.getQuizzesRef( function( quizzesRef ) {
var newQuizRef = quizzesRef.push();
newQuizRef.set({
title: quiz.title,
questions: quiz.questions,
published: quiz.published,
createdAt: firebase.database.ServerValue.TIMESTAMP,
createdBy: values.userEmail,
published: quiz.published
});
});
},
updateQuiz: function( quiz ) {
this.getQuizzesRef( function( quizzesRef ) {
var quizRef = quizzesRef.child( quiz.id );
quizRef.set( quiz );
});
},
getAllQuizzes: function( callback ) {
this.getQuizzesRef( function( quizzesRef ) {
quizzesRef.once( 'value' ).then( function( snapshot ) {
var quizEntries = snapshot.val();
if ( quizEntries !== null ) {
var quizzes = Object.keys( quizEntries ).map( function( key ) {
var quiz = quizEntries[key];
quiz.id = key;
return quiz;
});
callback( quizzes );
}
else {
callback( [] );
}
});
});
},
getQuizById: function( quizId, callback ) {
this.getQuizzesRef( function( quizzesRef ) {
quizzesRef.orderByKey().equalTo( quizId ).once( 'value' ).then( function( snapshot ) {
var responseData = snapshot.val();
if ( responseData && responseData[quizId] ) {
var quiz = responseData[quizId];
quiz.id = quizId
callback( quiz );
}
else {
callback( null );
}
});
});
}
};
module.exports = firebaseHelper;