FetchError:网络超时:https://db.fauna.com/

问题描述

我目前正在使用 netlify 在我的应用程序中托管某些逻辑。我已经阅读了 faunadb 的已知问题,并探索了解决方案,例如在函数体之外声明对象的实例。我已经尝试了建议的解决方案,但没有运气。我正在寻找头韵解决方案,因为随着应用程序的增长,这些错误变得频繁。

const faunadb = require('faunadb')
const q = faunadb.query
const client = new faunadb.Client({secret})

exports.handler = async (event,context) => {
  //body of function goes here
}

解决方法

我绝不肯定这会对您有所帮助,但实际上我一直在做相反的事情,将 Client 对象实例inside 包含在我的 Handler 中。

我收到了很多 HTTP_TIMEOUT 错误,因此我将所有内容移到处理程序中,错误不再出现。

不过,我不记得我在哪里读到的。但到目前为止它已经奏效了!

以下是我查询 FaunaDB 的 Netlify 函数之一,例如:

const headers = {
  'Access-Control-Allow-Origin': '*','Access-Control-Allow-Headers': 'Content-Type','Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE','Access-Control-Allow-Credentials': true,'Content-Type': 'application/json'
}

exports.handler = async (event) => {
  const { query,Client } = require('faunadb')
  const client = new Client({
    secret: process.env.FAUNADB_SECRET
  })
  
  console.log('Function `get-last-order` invoked')
  try {
    const response = await client.query(
      query.Paginate(query.Match(query.Index("orders_by_id_desc")),{ size: 1 })
    )
    console.log('success',response.data[0])
    /* Success! return the response with statusCode 200 */
    return {
      headers,statusCode: 200,body: JSON.stringify(response.data[0].id),}
  } catch (error) {
    console.log('error',error)
    /* Error! return the error with statusCode 400 */
    return {
      headers,statusCode: 400,body: JSON.stringify(error),}
  }
}

希望这对你有帮助。

另外需要注意的是,函数有 10 秒的执行限制。但如果您的函数运行时间超过 10 秒,您应该先尝试修复该问题。