-1

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});
  });
});
4

2 回答 2

0

onWrite():_

在实时数据库中创建、更新或删除数据时触发。

exports.createStripeCharge = functions.database.ref('/stripe_customers/{userId}/charges/{id}').onWrite((event) => {

因此,如果在上述位置写入数据库失败,则onWrite()不会触发。

此外,如果您希望它仅在添加数据时触发,则可以使用onCreate()

它在实时数据库中创建新数据时触发。

更多信息在这里:

https://firebase.google.com/docs/functions/database-events

于 2018-03-25T19:25:13.560 回答
0

数据库写入失败的唯一方法是它违反了安全规则,或者函数超时并在完成之前被清理。使用 admin SDK 时,安全规则不适用,因此这不是原因。我想写超时是有可能的,所以如果你对此非常担心,你应该增加函数的超时时间。发生超时的可能性极低。如果发生这种情况,您应该能够手动解决最终用户的问题,而不会浪费大量时间。

于 2018-03-25T19:39:45.867 回答