Firebase Cloud功能不一致CORS响应

时间:2018-06-08 21:26:27

标签: firebase cors google-cloud-functions

我在下面有这个云功能。它有99.99%的时间工作,但是如果该功能已经冷/闲一段时间,它的第一次调用将失败并且“崩溃”似乎无法进行任何注销。它返回到客户端时出现CORS错误,但我使用的是CORS包,它不应该抱怨CORS问题。

对该功能的后续调用将完美无缺,没有CORS投诉。我不确定这是Firebase Cloud Functions冷启动的问题,还是我对函数本身的代码有问题。

const admin = require('firebase-admin')
admin.initializeApp()
const functions = require('firebase-functions')
const cors = require('cors')({origin: true})

exports.placeOrder = functions.https.onRequest((req, res) => {
  return cors(req, res, () => {
    if (req.method !== 'POST') {
      return res.status(405).json({message: 'Not allowed'})
    }

    const customer = req.body.customer
    const token = req.body.token
    const productId = req.body.productId
    const address = req.body.address

    if (!_.every(['firstName', 'lastName', 'email'], _.partial(_.has, customer))) {
      console.error('Missing customer information')
      return res.status(400).json({message: 'Missing customer information'})
    }

    if (!_.every(['street', 'city', 'state', 'zipcode'], _.partial(_.has, address))) {
      console.error('Missing address information')
      return res.status(400).json({message: 'Missing address information'})
    }

    if (token.object !=='token') {
      console.error(req);
      return res.status(400).json({message: 'Missing payment token'})
    }

    if (customer && token && address && productId) {

      admin.firestore().collection('products').doc(productId).get().then(productDoc => {
        if (productDoc.exists) {
          // check the product can be bought. stock level? is active? price is not zero?
          const product = productDoc.data();
          if (!(product.price > 0 && product.isActive && product.stock > 0)) {
            return res.status(500).json({message: 'This product is not purchasable'})
          }

          const order = {
            token,
            address,
            customer,
            productRef: productDoc._ref,
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
            updatedAt: admin.firestore.FieldValue.serverTimestamp(),
          }

          return admin.firestore().collection('orders').add(order)
          .then(orderDoc => {
            order.productRef.set({stock: product.stock-1}, {merge: true})
            return res.status(200).json({
              message: 'Order placed',
              order: {
                id: orderDoc.id
              }
            })
          })
          .catch(err => {
            console.error(err);
            return res.status(500).json({message: 'Order could not be placed'})
          })

        } else {
          return res.status(500).json({message: 'Product does not exist'})
        }
      }).catch(err => {
        console.error(err);
        return res.status(500).json({message: 'DB error'})
      })
    } else {
      console.error(err);
      return res.status(400).json({message: 'Missing information'})
    }
  })
})

0 个答案:

没有答案