在 firebase 函数中实现服务器发送事件功能

Zac*_*ack 6 javascript firebase reactjs google-cloud-functions

我试图在 firebase 函数中实现服务器发送事件功能,在函数执行时它将不断地将数据发送回客户端,而不是在函数完成时发送回数据。我尝试过的所有操作都只是使函数在执行结束时返回任何数据。是否有可能将数据从 firebase 函数流回客户端,或者它是否缓存和缓冲所有内容,直到完成执行?是否有另一种方法可以使用 firebase 函数来以不同的方式执行此功能?

我试图在 firebase 函数中实现服务器发送事件功能,在函数执行时它将不断地将数据发送回客户端,而不是在函数完成时发送回数据。我尝试过的所有操作都只是使函数在执行结束时返回任何数据。

到目前为止,这是我的代码:

函数/index.js:

const functions = require("firebase-functions");
const express = require("express");

const app = express();

app.get("/sse", (request, response) => {
  // Set headers to indicate that the response is an SSE stream
  response.setHeader("Content-Type", "text/event-stream");
  response.setHeader("Cache-Control", "no-cache");
  response.setHeader("Connection", "keep-alive");

  // Send initial message to client
  response.write("data: Connected\n\n");

  // Send data to the client every second
  const intervalId = setInterval(() => {
    const data = { message: "Hello world!" };
    response.write(`data: ${JSON.stringify(data)}\n\n`);
    response.flush(); // Send buffered data to client immediately
  }, 1000);

  // End the response when the client closes the connection
  request.on("close", () => {
    clearInterval(intervalId);
    response.end();
  });
});

exports.sseFunction = functions.https.onRequest(app);
Run Code Online (Sandbox Code Playgroud)

然后是我在客户端的功能:

export const sseFunctionStream = async () => {
  const eventSource = new EventSource(
    "https://us-central1-<project-id>.cloudfunctions.net/sseFunction/sse"
  );

  eventSource.addEventListener("message", (event) => {
    const data = JSON.parse(event.data);
    console.log(data);
  });

  return () => {
    eventSource.close();
  };
};
Run Code Online (Sandbox Code Playgroud)

我尝试了几种实现,但它们都产生相同的结果,即事件侦听器在函数执行直至完成之前不会获取任何数据。一旦完成,它就会获取所有数据。我希望它在监听事件时每秒在客户端控制台记录“Hello World”,就像在函数中一样。

Eli*_*itz 4

由于缓冲机制,似乎不可能使 Firebase 功能支持 SSE/事件流。参考:/sf/answers/3390237791/

您可以考虑使用 Cloud Run、GAE 或写入 Firebase DB 作为替代方案。