【问题标题】:What should I return in an https callable function if it doesn't expect to return nothing如果不希望返回任何内容,我应该在 https 可调用函数中返回什么
【发布时间】:2020-11-25 12:55:16
【问题描述】:

我已经实现了一个 HTTPs (onCall) 函数,如果工作成功完成,它会向客户端抛出一些错误或返回 true。问题是我不明白为什么要返回 true(因为当我抛出错误时我不返回 false)。

由于HTTP协议要求向客户端返回响应以完成请求,我应该向客户端返回什么?我正在考虑删除我抛出的错误并返回一个经典的 HTTP 响应(状态代码、正文......)。

有什么想法吗?这是我正在做的事情:

exports.function = functions
  .region("us-central1")
  .runWith({ memory: "2GB", timeoutSeconds: 120 })
  .https.onCall(async (data, context) => {

        // Lazy initialization of the Admin SDK
        if (!is_function_initialized) {
          // ... stuff
          is_uploadImage_initialized = true;
        }
    
        // ... asynchronous stuff
    
        // When all promises has been resolved...
        // If work completed successfully
        return true;
    
       /*
         Is it correct instead ???
         return {code: "200 OK", date: date, body: message };
       */
    
    
       // Else, if errors
       throw new Error("Please, try again later.");
    
       /*
         Is it correct instead ???
         return {code: "418 I'm a teapot", date: date, body: message };
       */

   }

【问题讨论】:

    标签: javascript firebase google-cloud-platform google-cloud-functions


    【解决方案1】:

    doc中所述:

    要使用 HTTPS 可调用函数,您必须使用客户端 SDK 平台与functions.https 后端API(或实现 protocol)

    这意味着在任何情况下您都必须遵循该协议,因为客户端 SDK 确实实现了该协议。

    那么让我们看看关于要发送给客户端(即调用者或消费者)的响应的协议是什么:

    协议规定Response Body的格式如下:

    来自客户端端点的响应始终是 JSON 对象。在一个 最少包含dataerror,以及任何可选的 字段。如果响应不是 JSON 对象,或者不包含数据 或错误,客户端 SDK 应将请求视为失败 Google 错误代码 INTERNAL 。

    error - ....

    data - 函数返回的值。 这可以是任何有效的 JSON 值。 firebase-functions SDK 自动编码值 由用户以这种 JSON 格式返回。客户端 SDK 根据 序列化格式如下所述。

    如果存在其他字段,则应忽略它们。

    所以,要回答您的问题“我应该向客户端返回什么?”,您应该返回可以进行 JSON 编码的数据。另请参阅协议文档的section


    例如,如文档中所述,在 Callable Cloud 中您可以这样做

    return {
      firstNumber: firstNumber,
      secondNumber: secondNumber,
      operator: '+',
      operationResult: firstNumber + secondNumber,
    };
    //Excerpt of the doc
    

    或者,你可以这样做

    return {result: "success"}
    

    在您的特定情况下(“如果它不希望返回任何内容,我应该在 https 可调用函数中返回什么”)您可以很好地返回以下内容,正如您在问题中提到的那样:

    const date = new Date();
    const message = "the message";
    
    return { code: "200 OK", date: date, body: message };
    

    但您也可以使用 return true;return null;... 以某种方式由您决定在您的上下文中什么是有意义的。


    请注意,在您返回 { code: "200 OK", date: date, body: message } 的情况下,客户端不会将 code 的值视为 HTTP 响应代码,因为此 JSON 对象被注入到响应正文中。

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多