Skip to content

Instantly share code, notes, and snippets.

@sdymj84
Created November 21, 2018 22:54
Show Gist options
  • Save sdymj84/e72cb2b5e583b5daa10838ac3eea32db to your computer and use it in GitHub Desktop.
Save sdymj84/e72cb2b5e583b5daa10838ac3eea32db to your computer and use it in GitHub Desktop.
Firebase Cloud functions basic examples
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello Minjun!");
});
// Both of below lines return firestore database object
// admin.firestore() in cloud function
// db = getFirestore() in action creator
const createNotification = (notification) => {
return admin.firestore().collection('notifications').add(notification)
.then(doc => {
console.log('notification added', doc)
})
}
// function trigger for new project
exports.projectCreated = functions.firestore
.document('projects/{projectId}')
.onCreate(doc => {
const project = doc.data()
const notification = {
content: "New Project Created",
user: project.firstName + ' ' + project.lastName,
time: admin.firestore.FieldValue.serverTimestamp()
}
return createNotification(notification)
})
// function trigger for new user
exports.userJoined = functions.auth.user()
.onCreate(user => {
return admin.firestore().collection('users').doc(user.uid).get()
.then(doc => {
const newUser = doc.data()
const notification = {
content: "New User Joined",
user: newUser.firstName + ' ' + newUser.lastName,
time: admin.firestore.FieldValue.serverTimestamp()
}
return createNotification(notification)
})
})
// all "return" statement can be ommitted (will show warning though)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment