Firebase 在 GitHub 上提供了用于编写云函数的示例。我对“createStripeCharge”函数有疑问。写入数据库可能失败?如果是这种情况,此函数会向客户收费,但不会将任何对象保存到数据库中。这是正确的吗?这种错误处理还不够,还是我理解错了?
代码中的以下行让我感到困惑:
返回 event.data.adminRef.set(response);
您在 GitHub 上找到了代码: https ://github.com/firebase/functions-samples/blob/master/stripe/functions/index.js
或者在这里:
exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite((event) => {
const val = event.data.val();
// This onWrite will trigger whenever anything is written to the path, so
// noop if the charge was deleted, errored out, or the Stripe API returned a result (id exists)
if (val === null || val.id || val.error) return null;
// Look up the Stripe customer id written in createStripeCustomer
return admin.database().ref(`/stripe_customers/${event.params.userId}/customer_id`).once('value').then((snapshot) => {
return snapshot.val();
}).then((customer) => {
// Create a charge using the pushId as the idempotency key, protecting against double charges
const amount = val.amount;
const idempotency_key = event.params.id;
let charge = {amount, currency, customer};
if (val.source !== null) charge.source = val.source;
return stripe.charges.create(charge, {idempotency_key});
}).then((response) => {
// If the result is successful, write it back to the database
return event.data.adminRef.set(response);
}).catch((error) => {
// We want to capture errors and render them in a user-friendly way, while
// still logging an exception with Stackdriver
return event.data.adminRef.child('error').set(userFacingMessage(error));
}).then(() => {
return reportError(error, {user: event.params.userId});
});
});