firebase functions official examples
https://github.com/firebase/functions-samples
onCreate 을 사용하는 경우 새로 생성된 doc과 context가 되돌려 진다.
doc( DocumentSnapshot ) https://cloud.google.com/nodejs/docs/reference/firestore/0.11.x/DocumentSnapshot
promise error catch 하는 방법
admin.storage().bucket().file('path/to/file').download({
destination: 'temporary/file/path'
}).then(() => {
// Change the file and upload it.
}).catch(err => {
// Handle error(create file) if the file does not exist
})
firestore경로에 있는 문자열을 parameter로 사용하는 방법
exports.observeCreate = functions.firestore.document('/pathOne/{id}/pathTwo/{anotherId}').onCreate((snapshot, context) => {
console.log(context.params);
console.log(context.params.id);
});
notification and nested 작업
exports.observeCreate = functions.firestore.document('/pathOne/{id}/pathTwo/{anotherId}').onCreate(event => {
console.log(event.params);
//event prints out data but params undefined...
const data = event.data()
var id = event.params.id;
return admin.firestore().collection('path').doc(id).get().then(doc => {
const data = doc.data();
var fcmToken = data.fcmToken;
var message = {
notification: {
title: "x",
body: "x"
},
token: fcmToken
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
return;
})
.catch((error) => {
console.log('Error sending message:', error);
return;
});
return;
})
})
device에 notification 보내기
exports.sendNotification =
functions.firestore.document('Users/{userId}/Notifications/{notificationId}')
.onWrite((c hange, context) =>{
const userId = context.params.userId;
const notificationId = context.params.notificationId;
console.log('The User id is : ', userId);
console.log('The Notification id is : ', notificationId);
// ref to the parent document
return admin.firestore().collection("Users").doc(userId).collection("Token").doc(userId).get().then(queryResult => {
const tokenId = queryResult.data().deviceToken;
//const toUser = admin.firestore().collection("Users").doc(userId).collection("Notifications").doc(notificationId).get();
const notificationContent = {
notification:{
title: "/*App name */",
body: "You have a new Comment!",
icon: "default",
click_action: "/*Package */_TARGET_NOTIFICATION"
}
};
return admin.messaging().sendToDevice(tokenId, notificationContent).then(result => {
console.log("Notification sent!");
//admin.firestore().collection("notifications").doc(userEmail).collection("userNotifications").doc(notificationId).delete();
});
});
});
onwrite에 반응해서 특정topic으로 구분된 그룹에게 notification 보내기
exports.sendNotification = functions.firestore
.document('chats/{chatID}')
.onWrite((change, context) => {
// Get an object representing the document
console.log('chat triggered');
// perform desired operations ...
// See documentation on defining a message payload.
var message = {
notification: {
title: 'Hello World!',
body: 'Hello World!'
},
topic: context.params.chatID. //<- If you are using a CF version under v1.0 don't change here
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().send(message). //<- return the resulting Promise
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return true; //<- return a value
})
.catch((error) => {
console.log('Error sending message:', error);
//return. <- No need to return here
});
});
firestore에서 data fetch해서 가져오기
firestore.collection('products').doc(payment.product).get().then(product => {
if (!product.exists) {
console.log('No such product!');
} else {
console.log('Document data:', product.data());
}
})
function을 이용해서 firestore에 document만들기
exports.createProfile = functions.auth.user().onCreate((user) => {
var userObject = {
displayName : user.displayName,
email : user.email,
};
return admin.firestore().doc('users/'+user.uid).set(userObject);
});
firebase auth에 새로운 유저가 생성되는 경우에 따른 작업을 만들때
export const accountCreate = functions.auth.user().onCreate(user => {
console.log(user.data);
userDoc = {'email' = user.data.email,
'displayName' = user.data.displayName}
admin.firestore().collection('users').doc(user.data.uid)
.set(userDoc).then(writeResult => {
console.log('User Created result:', writeResult);
return;
}).catch(err => {
console.log(err);
return;
});
});