Last active
January 26, 2019 12:17
-
-
Save drKnoxy/060e586007e85abc1c235444d68c60e2 to your computer and use it in GitHub Desktop.
Moving a document and subcollection in a cloud function
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
import functions from "firebase-functions"; | |
import admin from "firebase-admin"; | |
// client code | |
// firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) { | |
// }) | |
admin.initializeApp(); | |
/** | |
* If we want to move a doc, and subcollection from one location to another | |
* /meetings/mid -> /archivedMeetings/mid | |
* /meetings/mid/tickets -> /archivedMeetings/mid/tickets | |
* https://us-central1-lets-point.cloudfunctions.net/archiveMeeting? | |
*/ | |
exports.archiveMeeting = functions.https.onRequest(async (req, res) => { | |
try { | |
const db = admin.firestore(); | |
// Do we have everything we need to do this | |
const { jwt = false, mid = false } = req.query; | |
if (jwt === false || mid === false) { | |
throw new Error('Missing some query params'); | |
} | |
// Is the user allowed to do this | |
const { uid } = await admin.auth().verifyIdToken(jwt); | |
const meetingRef = db.doc(`/meetings/${mid}`); | |
const archiveMeetingRef = db.doc(`/archivedMeetings/${mid}`); | |
const m = await meetingRef.get(); | |
if (!m.exists) throw new Error('Meeting dne'); | |
const isParticipant = m.data().participantIDs[uid] !== undefined; | |
if (!isParticipant) throw new Error('User must be in participant list'); | |
// Now we move the doc and subcollection | |
await db.runTransaction(async t => { | |
const [meeting, tickets] = await Promise.all([ | |
t.get(meetingRef).get(), | |
t.get(meetingRef).collection('tickets'), | |
]); | |
t.set(archiveMeetingRef, meeting.data()); | |
t.delete(meetingRef); | |
tickets.docs.forEach(ticket => { | |
t.create(archiveMeetingRef.collection('tickets').doc(ticket.id), ticket.data()); | |
t.delete(ticket.ref); | |
}); | |
// any return value is converted into a resolved promise | |
return null; | |
}); | |
res.status(200).send(); | |
} catch (err) { | |
console.error(err); | |
res.status(500).send(err); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment