Bernardstanislas
4/5/2016 - 12:38 PM

Squash hook as a bridge to firebase

Squash hook as a bridge to firebase

import Firebase from 'firebase';

const firebaseRef = new Firebase('https://squanalytics.firebaseio.com');
const pointsRef = firebaseRef.child('points');
const stanPointsRef = pointsRef.child('stan');
const arthurPointsRef = pointsRef.child('arthur');

export default async function (hook) {
    const currentTime = new Date();

    let {player, increment} = hook.params;
    increment = JSON.parse(increment);

    const respond = error => {
        if (error) {
            hook.res.status(500).json(error);
        } else {
            hook.res.json('ok');
        }
    };

    if (increment) {
        switch(player) {
            case 'stan':
                stanPointsRef.push().set({time: currentTime.getTime()}, respond);
                break;
            case 'arthur':
                arthurPointsRef.push().set({time: currentTime.getTime()}, respond);
                break;
            default:
                hook.res.status(404).json(`${player} does not exist`);
        }
    } else {
        switch(player) {
            case 'stan':
                stanPointsRef.orderByKey().limitToLast(1).once('child_added', snap => {
                    snap.ref().remove(respond);
                });
                break;
            case 'arthur':
                arthurPointsRef.orderByKey().limitToLast(1).once('child_added', snap => {
                    snap.ref().remove(respond);
                });
                break;
            default:
                hook.res.status(404).json(`${player} does not exist`);
        }
    }
}