gpt4 book ai didi

Firebase 云函数与 Firestore runTransaction 调用大约需要 30 秒才能完成

转载 作者:行者123 更新时间:2023-12-02 19:21:17 25 4
gpt4 key购买 nike

该函数首先进行 Stripe 调用来向用户收费,然后创建一个交易来更新两个不同的文档 - 相关的付款和用户。我不确定如何优化此代码,因为我需要事务逻辑来更新文档。如何优化这个功能?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const moment = require('moment')
admin.initializeApp(functions.config().firebase);
const stripe = require('stripe')(functions.config().stripe.testkey)
const db = admin.firestore();

exports.stripeCharge = functions.firestore
.document('users/{userId}/payments/{paymentId}')
.onWrite(event => {

const payment = event.data.data();
const userId = event.params.userId;
const paymentId = event.params.paymentId;

if (!payment || payment.charge) return;

const amount = payment.amount;
const duration = payment.duration;
const createdAt = payment.createdAt;
const idempotency_key = paymentId;
const source = payment.token.id;
const currency = 'usd';
const charge = {amount, currency, source};

return stripe.charges.create(charge, { idempotency_key })
.then(charge => {
if (!charge) return;

var userRef = db.collection('users').doc(userId);
var paymentsRef = userRef.collection('payments').doc(paymentId);
var transaction = db.runTransaction(t => {
return t.get(userRef)
.then(doc => {
let expiresAt;
if(doc.data().expiresAt
&& moment(doc.data().expiresAt).isAfter(createdAt)){
expiresAt = moment(doc.data().expiresAt).add(duration, 'M').toDate();
}else{
expiresAt = moment(createdAt).add(duration, 'M').toDate();
}
t.update(userRef, {
expiresAt: expiresAt,
timestamp: moment().toDate()
});
t.update(paymentsRef, { charge: charge });
});
})
.then(result => {
console.log('Successful');
})
})
.catch(err => { console.log(err) })

});

最佳答案

返回交易本身解决了问题。

所以代替这个:

var transaction = db.runTransaction(t => {
return t.get(userRef)
//...

这样做:

return db.runTransaction(t => {
return t.get(userRef)
//...

关于Firebase 云函数与 Firestore runTransaction 调用大约需要 30 秒才能完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46881709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com