Skip to content

Instantly share code, notes, and snippets.

@andresmijares
Last active May 5, 2019 21:14
Show Gist options
  • Save andresmijares/912651350267c64c75aaa9129ef98d3b to your computer and use it in GitHub Desktop.
Save andresmijares/912651350267c64c75aaa9129ef98d3b to your computer and use it in GitHub Desktop.
Batch Op
const functions = require('firebase-functions')
const admin = require('firebase-admin')
const uuidv1 = require('uuid/v1')
const _ = require('_')
admin.initializeApp()
const db = admin.firestore()
export const onboard = functions.firestore
.document(`onboard/{doc}`)
.onUpdate((change, context) => {
const data = change.after.data()
if (data.status === 'draft' || data.status === 'completed') {
// ! Not ready to process yet or alredy processed
return Promise.resolve()
} else if (data.status === 'ready') {
return execOnboard(data)
} else if (data.status === 'fail') {
// ! We need an exit clouse in case the onboard keep failing
if (data.retry >= 3) {
return Promise.resolve()
} else {
return execOnboard(data)
}
}
})
const execOnboard = data => {
const batch = db.batch()
const venueId = uuidv1()
const services = data.services
const promotions = data.promotions
const servicesRef = db.collection(`services`)
// ! Create all services docs
for (let service of services) {
}
const promotionsRef = db.collection(`promotions`)
// ! Create all promitions docs
for (let promotion of promotions) {
const _id = uuidv1()
const promotionRef = promotionsRef.doc(`${_id}`) // ! set the promotion inique id
batch.set(promotionRef, Object.assign({}, promotion, {
_id, // ! promotion unique id
venue_id: venueId // ! create the relation with the venue
}))
}
// ! Create Venue
const venuesRef = db.collection(`venues`)
const venueRef = venuesRef.doc(`${venueId}`) // ! set the venue inique id
const venue = _.omit(data, ['services', 'promotions'])
batch.set(venueRef, venue, {
_id: venueId
})
// ! update the onboard status
const onboardsRef = db.collection(`onboard`)
const onboardRef = onboardsRef.doc(`${data._id}`)
batch.update(onboardRef, {
status: `completed`
})
return batch
.commit()
.catch(e => {
const retry = _.isNil(data.retry) ? 0 : data.retry
return db.collection(`onboard`)
.doc(data._id)
.update({
status: `fail`,
retry: retry + 1
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment