Showing Mail Statistics Using Firebase In Badgeyay
In this blog post I will show how we implemented mail statistics on the admin dashboard of Badgeyay. The problem is that we cannot send a request to an external API from firebase cloud functions in free plan and secondly we have to them bypass the call to realtime database and design a logic to sort out the details from the realtime database using python admin sdk. So, our approach in solving this is that we will use the realtime database with the cloud functions to store the data and using the firebase admin sdk will sort the entries and using binary search will count the statistics efficiently..
Procedure
- Configuring the database URL in admin SDK
firebase_admin.initialize_app(cred, { ‘storageBucket’: ‘badgeyay-195bf.appspot.com’, ‘databaseURL’: ‘https://badgeyay-195bf.firebaseio.com’ }) |
- Write the mail data in realtime database using cloud function on promise resolvement
function writeMailData(uid, state, reason) { if (state === ‘success’) { db.ref(‘mails’) .push() .set({ … }); |
- Fetching the mail data from the realtime database in python admin sdk
def get_admin_stat(): mail_ref = firebasedb.reference(‘mails’) mail_resp = mail_ref.get() … |
This will fetch the current date and them generates the relative dates in past. Then it filters out the data using a for loop and a comparison statement with the date to get the count of the mails. Those count is then passed into a dict and sent through schema.
- Fetching the mail stats in admin index panel
mails : await this.get(‘store’).queryRecord(‘admin-stat-mail’, {}) |
- Showing mails on the index page
class=“six wide column”>
div class=“ui fluid center aligned segment”> h3 class=“ui left aligned header”> Messages h3> div class=“ui divider”>div> h3 class=“ui header”> No. of Sent Mails h3> table class=“ui celled table”> tbody> tr> td> In last 24 hourstd> td class=“right aligned”> {{model.mails.lastDayCount}} td> tr> tr> td>In last 3 daystd> td class=“right aligned”> {{model.mails.lastThreeDays}} td> tr> tr> td> In last 7 days td> td class=“right aligned”> {{model.mails.lastSevenDays}} td> tr> tr> td> In last 1 month td> td class=“right aligned”> {{model.mails.lastMonth}} td> tr> tbody> table> div> |
PR to the issue: https://github.com/fossasia/badgeyay/pull/1163
Benefits of the approach
This approach is best in the case, when we only are using a subset of services firebase offers and do not want to pay for the services that are not required by the system.
Resources
- Link to Issue – https://github.com/fossasia/badgeyay/issues/1136
- Realtime database – https://firebase.google.com/docs/database/admin/save-data
- Fetching the data from admin sdk in api – https://firebase.google.com/docs/database/admin/retrieve-data