NodeJS 无法成功分析通过/__/quitquitquit函数代码库请求的Firebase函数关闭,它可能有语法或运行时错误

ivqmmu1c  于 2023-08-04  发布在  Node.js
关注(0)|答案(6)|浏览(106)

我正在尝试部署我的功能。我添加了第二个并重构了第一个,现在我无法部署。我尝试绕过CI/CD手动部署,但仍然出现错误。这是一个2.0的函数,我运行了tsc。自从上次部署后,我重新安装了firebase-tools包。除了我提到的,没有什么不同,当它确实工作。
以下是firebase deploy --only functions的输出:

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> lint
> eslint --ext .js,.ts .

Running command: npm --prefix "$RESOURCE_DIR" run build

> build
> tsc

✔  functions: Finished running predeploy script.
i  functions: preparing codebase default for deployment
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
i  artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
✔  artifactregistry: required API artifactregistry.googleapis.com is enabled
i  functions: Loading and anaylzing source code for codebase default to determine what to deploy
Serving at port 8907

shutdown requested via /__/quitquitquit

Error: Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

字符串
我的代码:

/* eslint-disable max-len */
import "dotenv/config";
import { initializeApp } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore";
import { onDocumentCreated, onDocumentDeleted } from "firebase-functions/v2/firestore";

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;

// eslint-disable-next-line @typescript-eslint/no-var-requires
const client = require("twilio")(accountSid, authToken);

export const sendSMSOnContactWrite = onDocumentCreated("/contact/{contactSubmissionId}", async (event) => {
  const data = event.data?.data();
  console.log(data);
  return await client.messages.create({
    // eslint-disable-next-line
    "body": `New contact submission from ${data?.name} at ${data?.email} with message: ${data?.message}. ${data?.name} said ${data?.hasWebsite} when asked if they have a website.${data?.hasWebsite === "yes" ? " Their website is at " + data?.websiteAddress : ""}`,
    "from": twilioPhoneNumber,
    "to": process.env.MY_PHONE_NUMBER,
  });
});

export const sendSMSOnContentItemDelete = onDocumentDeleted("/websites/{websiteId}/content/{contentGroupId}/data/{contentId}", async (event) => {
  initializeApp();
  const db = getFirestore();
  const websiteDocRef = db.doc("websites/" + event.params.websiteId);
  const websiteDoc = await websiteDocRef.get();
  const websiteDocData = websiteDoc.data();
  if (!websiteDocData) {
    // TODO: Log error
    return;
  }
  const users = websiteDocData["users"];
  for (const userId of users) {
    const userDocRef = db.doc("users/" + userId);
    const userDoc = await userDocRef.get();
    const userDocData = userDoc.data();
    if (!userDocData) {
      // TODO: Log error
      return;
    }
    const deletionPreference = userDocData["preferences"]["deletion_sms"];
    if (deletionPreference) {
      const data = event.data?.data();
      console.log(data);
      return await client.messages.create({
        "body": `Content item with title ${data?.title} was deleted from website ${websiteDocData["url"]}`,
        "from": twilioPhoneNumber,
        "to": userDocData["phone_number"],
      });
    } else {
      return;
    }
  }
});

kt06eoxx

kt06eoxx1#

如果您正在使用第二代的Cloud Functions:
检查您是否正确使用onRequest()函数。我得到了同样的错误,因为我声明了我的函数错误。
执行exports.functionName = onRequest((data, context) => { ...而不是exports.functionName = functions.onRequest((data, context) => { ...
并通过const {onRequest} = require("firebase-functions/v2/https");导入

rggaifut

rggaifut2#

在我的例子中,我不得不将const firestore = admin.firestore();移动到函数内部,而不是将它放在函数外部。

2exbekwf

2exbekwf3#

我们找到了解决方案和原因:在部署时访问函数配置参数。
显然,它们只能在运行时访问,而不是部署时。将这些访问移到实际的函数代码中可以使事情再次工作。

ua4mk5z4

ua4mk5z44#

在我的例子中,我在使用firebase-tools <= 12.4.4时使用NodeJS v20.0.0
之前,我在使用firebase-tools <= 12.4.4时尝试了Node v19.5.0,并且能够顺利部署。
今天,我尝试使用NodeJS v20.0.0并安装了npm install firebase-tools@12.4.5 --save。我这边不会再有部署错误了。

wbgh16ku

wbgh16ku5#

在我的情况下,它是松弛螺栓API。

const { App, ExpressReceiver } = require('@slack/bolt');
const app = new App({
    token: process.env.SLACK_BOT_TOKEN,
    signingSecret: process.env.SLACK_SIGNING_SECRET,
});

字符串
由于参数被设置为secret,因此如果部署此代码,应该可以正常工作

firebase functions:secrets:set SECRET_NAME


然而,似乎firebase deploy在代码库分析期间未能应用这些秘密,因此螺栓应用程序在没有所需参数的情况下崩溃。
我的解决方案是使用本地.env,只是为了通过分析,

const { App, ExpressReceiver } = require('@slack/bolt');
require('dotenv').config();

const app = new App({
    token: process.env.SLACK_BOT_TOKEN,
    signingSecret: process.env.SLACK_SIGNING_SECRET,
});


但是将其排除在firebase.json中部署。

"ignore": [
        ".env",
   ]

tf7tbtn2

tf7tbtn26#

由于初始化不正确,Firebase函数可能遇到困难。要解决此问题,建议您在index.js文件中全局初始化Firebase应用程序。
您应该将以下代码添加到index.js:

// Initialize Firebase app globally:
const admin = require('firebase-admin');
const functions = require('firebase-functions');

if (admin.apps.length === 0) {
  admin.initializeApp(functions.config().firebase);
}

字符串
上面的代码片段检查是否已初始化任何Firebase应用程序。如果不是(admin.apps.length === 0),它将使用Firebase配置初始化应用程序。
此外,如果您的函数尚未全局初始化,则还应确保初始化Firebase。您可以通过向函数中添加以下代码来完成此操作:

if (admin.apps.length === 0) {
  admin.initializeApp();
}


通过执行这些步骤,您可以确保您的Firebase函数不会因缺乏正确的初始化而关闭。

相关问题