firebase HttpsFunction 的请求处理程序的正确类型是什么?

cbd*_*per 5 node.js firebase typescript google-cloud-functions

我需要将我的函数分成多个文件。

这是我的index.ts

export const helloWorld = functions.https.onRequest((request, response) => {
  functions.logger.info("Hello logs!", {structuredData: true});
  response.send("Hello from Firebase!");
});
Run Code Online (Sandbox Code Playgroud)

我需要它是这样的:

import helloWorldHandler from "./handlers/helloWorldHandler"

export const helloWorld = functions.https.onRequest(helloWorldHandler);
Run Code Online (Sandbox Code Playgroud)

那么我应该在helloWorldHandler请求处理程序中输入什么?

const helloWorldHandler : ??? = async (req,res) => {
  const result = await someApi();
  functions.logger.info("Hello logs!", {structuredData: true});
  res.send("Hello from Firebase!");
};

export default helloWorldHandler;
Run Code Online (Sandbox Code Playgroud)

我试过:

import * as functions from "firebase-functions";

const helloWorldHandler : functions.HttpsFunction = async (req,res) => { ... };
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

类型“(req: Request, res: Response) => Promise<Response>”不可分配给类型“HttpsFunction”。

类型“(req: Request, res: Response) => Promise<Response>”中缺少属性“__trigger”,但类型“TriggerAnnotated”中需要属性“__trigger”。

onRequest()方法(应将处理程序作为参数的方法)似乎没有为其提供正确的类型名称,而不是函数签名。我需要为此创建一个别名吗?

在此输入图像描述

sam*_*man 4

该类型functions.HttpsFunction是 的返回类型functions.https.onRequest(),而不是它的参数。这种类型的函数由您的代码导出,并定义 Firebase CLI 需要部署的内容(区域、内存大小等存储在属性中__trigger)。

由于您想要第一个参数的类型functions.https.onRequest(),因此您正在寻找类型:

type HttpsOnRequestHandler = (req: functions.https.Request, resp: functions.Response<any>) => void | Promise<void>
Run Code Online (Sandbox Code Playgroud)

但您可以使用以下任一方法从 Firebase 函数库中提取它,而不是对其进行硬编码:

import * as functions from "firebase-functions";

type HttpsOnRequestHandler = Parameters<typeof functions.https.onRequest>[0];
Run Code Online (Sandbox Code Playgroud)

或者

import { https } from "firebase-functions";

type HttpsOnRequestHandler = Parameters<typeof https.onRequest>[0]
Run Code Online (Sandbox Code Playgroud)

注意:如果您的代码本身不使用firebase-functions库,您可以告诉 TypeScript 您只希望使用import type * as functions from "firebase-functions";适当import type { https } from "firebase-functions";的类型;这会从已编译的 JavaScript 中删除导入,因为运行代码不需要导入。