我已经使用了Firebase云功能和twilio短信功能。
此代码效果很好,但只有我不明白如何在实时数据库中更新相同记录
exports.textStatus = functions.database
.ref('/sms_messages/{UID}').onCreate((change, event) => {
const UID = event.params.UID;
return admin.database().ref(`/sms_messages/${UID}`).once('value').then(snapshot => snapshot.val()).then(msg => {
const status = msg.status
const phoneNumber = msg.number
// validate phone number
if ( !validE164(phoneNumber) ) {
throw new Error('number must be E164 format!')
}
const textMessage = {
body: `Velkommen til Club Nautic Booking. Du kan logge ind med ${status} og adgangskoden`,
to: phoneNumber, // Text to this number
from: twilioNumber // From a valid Twilio number
}
return client.messages.create(textMessage)
})
.then(message => {
console.log(message.sid, 'success');;
})
.catch(err => {
console.log(err);
})
});
因此,如果发送了短信,我想更新数据库状态=已发送(msg.status)
console.log(message.sid, 'success');
但不知道如何在此处获取引用并更新相同的子节点..因此状态将更改为已发送或未发送
答案 0 :(得分:0)
// onCreate includes (snapshot, context)
// https://firebase.google.com/docs/functions/database-events#handle_event_data
exports.textStatus = functions.database.ref('/sms_messages/{MSG_ID}')
.onCreate((snapshot, context) => {
const MSG_ID = context.params.MSG_ID;
// const msg = snapshot.val(); // Using Promise.resolve to retain catch()
return Promise.resolve(snapshot.val())
.then(msg => {
const status = msg.status;
const phoneNumber = msg.number;
// validate phone number
if (!validE164(phoneNumber)) {
throw new Error('number must be E164 format!'); // This is reason for resolve
}
const textMessage = {
body: `Velkommen til Club Nautic Booking. Du kan logge ind med ${status} og adgangskoden`,
to: phoneNumber, // Text to this number
from: twilioNumber // From a valid Twilio number
}
return client.messages.create(textMessage);
})
.then(message => {
console.log(message.sid, 'success');
// https://firebase.google.com/docs/reference/functions/functions.database.DataSnapshot#ref
return snapshot.ref.child('sent').set(true);
})
.catch(err => {
console.log(MSG_ID, err);
// sent sent to false, include error message for reference
let error_promises = [
snapshot.ref.child('sent').set(false),
snapshot.ref.child('err_msg').set(err)
];
return Promise.all(error_promises);
// alternatively, just set to false
// return snapshot.ref.child('sent').set(false);
})
});