Skip to content

Instantly share code, notes, and snippets.

@andresmijares
Created May 5, 2019 21:41
Show Gist options
  • Save andresmijares/315e46765acc12e58db0a2a4c50c7697 to your computer and use it in GitHub Desktop.
Save andresmijares/315e46765acc12e58db0a2a4c50c7697 to your computer and use it in GitHub Desktop.
Banking
const functions = require('firebase-admin')
const admin = require('firebase-admin')
const uuidv1 = require('uuid/v1')
admin.initializeApp()
const db = admin.firestore()
export const execPurchase = functions.https.onCall(async (data, context) => {
const userId = context.auth.uid
if (!userId) {
throw new Error(`Missing Authentication`)
}
const { itemId, quantity } = data
const purchaseID = uuidv1()
const userRef = await db.collection(`users`).doc(userId)
const itemRef = await db.collection(`items`).doc(itemId)
const purchaseRef = await db.collection(`purchases`).doc(purchaseID)
// ! check if the
return db.runTransaction((transaction) => {
return transaction.get(userRef).then((userDoc) => { // ! lock user data
// ! get the item information
const itemDoc = transaction.get(itemRef)
// ! check if user can buy
const { coins, _id: userId } = userDoc.data()
const { price, id: itemId, name, quantity: availableQuantity } = itemDoc.data()
const total = price * quantity
const canBuy = total < coins
if (!canBuy) throw new Error(`Not enough coins`)
// ! check if there are enough quantities
const enoughQuantity = availableQuantity <= quantity
if (!enoughQuantity) throw new Error(`Not enough ${name}`)
// ! update collections with new values
transaction.update(userRef, {
coins: coins - total
})
transaction.update(itemRef, {
quantity: availableQuantity - quantity
})
// ! register the purchase
transaction.set(purchaseRef, {
user_id: userId,
item_id: itemId,
quantity,
total
})
// ! we are done! let's execute all the operations
})
})
}).then(result => {
console.log('Transaction success!')
}).catch(err => {
console.log('Transaction failure:', err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment