Last active
January 29, 2018 02:06
-
-
Save dheffx/6d36af2deb0513a1189aedf2f26af5b4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const _ = require("lodash") | |
const firebase = require('firebase-admin') | |
//firebase config | |
const config = require('./config') | |
//firebase credentials | |
const serviceAccount = 'credentials.json' | |
firebase.initializeApp({ | |
credential: firebase.credential.cert(serviceAccount), | |
databaseURL: config.firebase.databaseURL | |
}) | |
let db = firebase.database() | |
let users = db.ref('users') | |
let payments = db.ref('payments') | |
let transactions = payments.child('transactions') | |
let minimum = 85 | |
let vig = .1 | |
//Testing | |
users.set(null) | |
payments.set({ pool: { balance: 0 }, transactions: [] }) | |
users.on('child_changed', checkForAutoPayment) | |
transactions.on('child_added', processPendingTransactions) | |
_.times(50, function() { | |
users.push(mockuser()) | |
}) | |
function checkForAutoPayment(snap) { | |
let user = snap.val() | |
if (user.balance >= minimum) { | |
let fee = user.balance * vig | |
let payout = user.balance - fee | |
transactions | |
.push({ | |
created: firebase.database.ServerValue.TIMESTAMP, | |
to: snap.key, | |
amount: user.balance, | |
fee: fee, | |
payout: payout | |
processed: false | |
}) | |
snap.ref.update({ balance: 0 }) | |
} | |
} | |
function processPendingTransactions (snap) { | |
/* | |
* Here is where the business logic would go | |
*/ | |
snap.ref.update({ | |
completed: firebase.database.ServerValue.TIMESTAMP, | |
processed: true, | |
}) | |
payments.child('pool').once('value').then(function(poolSnap) { | |
let pool = poolSnap.val() | |
poolSnap.ref.update({balance: pool.balance + fee}) | |
}).catch(function(e) { console.error(e)} ) | |
} | |
//firebase.app().delete() | |
function mockuser () { | |
return { | |
name: Math.random().toString(36).substring(7), | |
balance: Math.random() * 100 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment