JavaScript Azure 函数中的 if 语句不起作用

if statement inside JavaScript Azure Function not working

目标

我公司使用外联网平台,让客户 post "ideas" 进行产品增强。我们希望 post 在 Slack 中通知这些想法。 Extranet 平台不提供想法的 webhook。它确实提供了一个想法 API。但是,它不提供查询在两个时间戳之前、之后或之间创建的想法的方法。创意 API 将创意创建日期 return 作为时间戳,如下所示:2018-11-13T02:03:31.583。它还 return 是 post 提出想法的作者的名字和想法的文本。

我能想到的最佳解决方案是使用 Azure 逻辑应用程序:

代码

输入

(我在 JSON 中留下了其他想法元数据,例如作者和文本,以简化我的问题)

{
    "date": "2018-12-12T17:34:07.693"
}

Azure 函数index.js

module.exports = function (context, data) {
    var ideaDate = data.body;

    var ideaDate2 = JSON.stringify(ideaDate);
    var ideaDate3 = JSON.parse(ideaDate2);
    var ideaDate4 = ideaDate3.date;
    // Extract date only
    var ideaDate5 = ideaDate4.substring(0, 10);

    // Get today's date
    var todaysDate = new Date();
    var localDate = new Date(todaysDate);
    var localDate1 = localDate.toISOString().toString()
    // Extract date only
    var localDate2 = localDate1.substring(0, 10);


    ///PROBLEMATIC LINE
    if (new String(ideaDate5).valueOf() === new String(localDate2).valueOf()) {

        // Response of the function to be used later
        context.res = {
            body: {
                ideaDate,
                ideaDate2,
                ideaDate3,
                ideaDate4,
                ideaDate5,
                todaysDate,
                localDate,
                localDate1,
                localDate2
            }
        };
    }

    context.done();
};

输出

500: Internal Service Error

没有问题 if 语句行的成功输出

我在输出中包含所有变量以演示脚本运行时发生的情况。

{
    "ideaDate": {
        "date": "2018-12-12T17:34:07.693"
    },
    "ideaDate2": "{\"date\":\"2018-12-12T17:34:07.693\"}",
    "ideaDate3": {
        "date": "2018-12-12T17:34:07.693"
    },
    "ideaDate4": "2018-12-12T17:34:07.693",
    "ideaDate5": "2018-12-12",
    "todaysDate": "2018-12-12T23:51:26.110Z",
    "localDate": "2018-12-12T23:51:26.110Z",
    "localDate1": "2018-12-12T23:51:26.110Z",
    "localDate2": "2018-12-12"
}

我是 JavaScript

的新手

感谢您提供任何检测问题的建议或完全推荐更好的流程。

编辑

感谢 ABOS 指出 if 语句必须用括号括起来。我在上面打印的代码中添加了这些。 Azure 函数不再是 return 错误。但是,它不会 return 输出中的 JSON 字段。

但我很感激能更近一步。

编辑 2

function.json 在 Azure 函数中:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

根据当前 UTC 时间更改输入日期,代码应 return JSON 正文符合预期。以及对您的代码的一些改进。

module.exports = function (context, data) {
    var ideaDate = new Date(data.body.date).toISOString().substring(0, 10);
    var todaysDate  = new Date().toISOString().substring(0, 10);

    if (ideaDate === todaysDate) {

        context.res = {
            body: {
               ideaDate,
               todaysDate
            }
        };
    }

    context.done();
};