Created
November 21, 2018 22:54
-
-
Save sdymj84/e72cb2b5e583b5daa10838ac3eea32db to your computer and use it in GitHub Desktop.
Firebase Cloud functions basic examples
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
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