Created
February 2, 2018 16:14
-
-
Save joserocha3/de69124865bf25b634f3f3bad3ef17c3 to your computer and use it in GitHub Desktop.
Use map instead of forEach with a firestore snapshot
This file contains 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
exports.recurringPayment = functions.https.onRequest(async (req, res) => { | |
const hook = req.body.type | |
const data = req.body.data.object | |
// 300 or 400 as failed will cause stripe to rerun | |
if (!data) return res.status(400).send('data missing') | |
if (!data.subscription) return res.status(200).send('not a subscription') | |
if (hook !== 'invoice.payment_succeeded' && hook !== 'invoice.payment_failed') return res.status(400).send('unknown hook') | |
const status = hook === 'invoice.payment_succeeded' ? 'active' : 'pastDue' | |
try { | |
const doc = await admin.firestore().collection('subscriptions').doc(data.subscription).get() | |
await Promise.all(snapshot.docs.map(async doc => { | |
try { | |
await admin.firestore().collection('subscriptions').doc(doc.id).update({status: status}) | |
await admin.firestore().collection('users').doc(doc.data().uid).update({'subscription.status': status}) | |
return res.status(200).send('done') | |
} catch (error) { | |
console.log('admin.database().collection(subscriptions).doc().update()', error) | |
return res.status(400).send(error.stack) | |
} | |
})) | |
} catch (error) { | |
console.log('admin.firestore().collection(subscriptions).where().get()', error) | |
return res.status(500).send(error.stack) | |
} | |
return res.status(200).send({ | |
message: `success`, | |
query: req.query, | |
data: data | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment