Azure function run code on startup for Node

帅比萌擦擦* 提交于 2021-02-08 07:37:25

问题


I am developing Chatbot using Azure functions. I want to load the some of the conversations for Chatbot from a file. I am looking for a way to load these conversation data before the function app starts with some function callback. Is there a way load the conversation data only once when the function app is started?

This question is actually a duplicate of Azure Function run code on startup. But this question is asked for C# and I wanted a way to do the same thing in NodeJS


回答1:


You can use global variable to load data before function execution.

var data = [1, 2, 3];

module.exports = function (context, req) {
    context.log(data[0]);
    context.done();
};

data variable initialized only once and will be used within function calls.




回答2:


I have a similar use case that I am also stuck on.

Based on this resource I have found a good way to approach the structure of my code. It is simple enough: you just need to run your initialization code before you declare your module.exports.

https://github.com/rcarmo/azure-functions-bot/blob/master/bot/index.js

I also read this thread, but it does not look like there is a recommended solution.

https://github.com/Azure/azure-functions-host/issues/586

However, in my case I have an additional complication in that I need to use promises as I am waiting on external services to come back. These promises run within bot.initialise(). Initialise() only seems to run when the first call to the bot occurs. Which would be fine, but as it is running a promise, my code doesn't block - which means that when it calls 'listener(req, context.res)' it doesn't yet exist.

The next thing I will try is to restructure my code so that bot.initialise returns a promise, but the code would be much simpler if there was a initialisation webhook that guaranteed that the code within it was executed at startup before everything else.

Has anyone found a good workaround?

My code looks something like this:

var listener = null;

if (process.env.FUNCTIONS_EXTENSION_VERSION) {
    // If we are inside Azure Functions, export the standard handler.
    listener = bot.initialise(true);

    module.exports = function (context, req) {
        context.log("Passing body", req.body);
        listener(req, context.res);
    }
} else {
    // Local server for testing
    listener = bot.initialise(false);
}


来源:https://stackoverflow.com/questions/48815835/azure-function-run-code-on-startup-for-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!