【问题标题】:Error calling a TypeScript function in firebase cloud function在 Firebase 云函数中调用 TypeScript 函数时出错
【发布时间】:2022-02-05 21:37:47
【问题描述】:

我在为 firebase 云函数编写打字稿代码时遇到了一些问题。 我认为这主要是语法问题。

代码如下,但相关部分是关于 myLocalFunc 函数的调用。其余的只是在这里提供一些上下文。部分阅读:

response:Response<any>

在:

const myLocalFunc = (mail:string, flag:boolean, response:Response<any>) => {...}

错了。因为我收到此错误消息:

error TS2315: Type 'Response' is not generic.

正确的语法是什么?

const myLocalFunc = (mail:string, flag:boolean, response:Response<any>) => {
    admin.auth().getUserByEmail(mail)
        .then(function(userRecord) {
          // Do some useful work.
          const data = {
            boolField: flag,
          };
          const refStr = "/Users/"+userRecord.uid;
          admin.database().ref(refStr).set(data);
        })
        .catch(function(error) {
          console.log("Error fetching user data:", error);
          let rspMsg = "This user (";
          rspMsg += mail;
          rspMsg += ") does not exists.";
          response.send(rspMsg);
        });
  };
  
  
  exports.myFunc = functions.https.onRequest(function(req, resp) {
  resp.set("Access-Control-Allow-Origin", "*");
  resp.set("Access-Control-Allow-Methods", "GET, POST");

  corsHandler(req, resp, async () => {
    const from = String(req.body.from);
    const idToken = String(req.body.token);

    admin.auth().verifyIdToken(idToken)
        .then(function(decodedToken) {
          const uid = decodedToken.uid;
          const refStr = "/Users/"+uid;
          const ref = admin.database().ref(refStr);

          ref.on("value", function(snapshot) {
            console.log("snapshot.val():", snapshot.val());
            if (snapshot.val() !== undefined) {
              const snv = snapshot.val();
              if (snv.adminRights !== undefined) {
                if (snv.adminRights) {
                  // Only if we reach this point,
                  // can we perform the operation next line.
                  myLocalFunc(from, true, resp);
                }
              }
            }
          }, function(errorObject) {
            console.log("The read failed: " + errorObject);
          });
        }).catch(function(error) {
          // Handle error
          functions.logger.log("(FL)error:", error);
          console.log("(CL)error:", error);
        });
  }); // End corsHandler.
});

注意:

在阅读了一些 functions.https.onRequest 的文档后,我有了尝试 Response 类型的想法(没有太多信念)。

如果我将代码更改为:

const myLocalFunc = (mail:string, flag:boolean, response) => {...}

这实际上是我开始的。

我收到此错误:

error TS7006: Parameter 'response' implicitly has an 'any' type.

如果我尝试将代码更改为:

const myLocalFunc = (mail:string, flag:boolean, response:Response) => {...}

我得到这两个错误:

37:18 - error TS2339: Property 'send' does not exist on type 'Response'.
37         response.send(rspMsg); // This works.
                ~~~~

79:46 - error TS2345: Argument of type 'Response<any>' is not assignable to parameter of type 'Response'.
Type 'Response<any>' is missing the following properties from type 'Response': headers, ok, redirected, statusText, and 9 more.

79                   myLocalFunc(from, true, resp);

【问题讨论】:

  • 试试response:Response 没有&lt;any&gt; 或者你能显示响应从哪里导入?
  • 我建议编辑问题以显示重现此问题的完整、最小示例。显示整个文件,并删除不直接属于问题的所有内容。您还应该显示您的 package.json,以便我们可以看到您正在使用的库的版本。 stackoverflow.com/help/minimal-reproducible-example
  • myLocalFunc的最后一个参数来自functions.https.onRequest(function(req, resp)的最后一个参数,也就是resp。我想我只需要在myLocalFunc原型中写它的类型(或签名)。我还在帖子末尾添加了注释,请看一下。
  • 我不会从任何地方导入响应。我只需要为最后一个参数输入一个类型,并且非常知道要输入什么。
  • 尝试import { Response } from "express",然后在此处使用Response作为类型。

标签: node.js typescript google-cloud-functions typescript-generics


【解决方案1】:

onRequest() 中的reqres 参数是来自Express 的RequestResponse 对象。当不从 Express 导入响应时,它是另一个接口,也不是通用的。

import {Response} from "express";

const myLocalFunc = (mail: string, flag: boolean, response: Response) => {...}

【讨论】:

  • 我把第一行“Response”两边的空格去掉了,否则不起作用。
  • 这可能是您的代码格式化程序,带有一些警告。
猜你喜欢
  • 2019-01-18
  • 2020-03-26
  • 2020-02-03
  • 2020-07-12
  • 2021-09-13
  • 2021-08-29
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多