Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the result of an Azure Function

I'm starting with Azure Functions. I have the following code:

module.exports = function (context, req) 
    {
        context.log('JavaScript HTTP trigger function processed a request.');

        context.log(context.req.body.videoId)
        if (context.req.body.videoId =! null) 
        {
            context.log('inicia a obtener comentarios')

             const fetchComments = require('youtube-comments-task')

            fetchComments(req.body.videoId)
            .fork(e => context.log('ERROR', e), p => {                   
                        context.log('comments', p.comments)
                        })        

             context.res = { body: fetchComments.comments }
        }
        else {
            context.res = {
                status: 400,
                body: "Please pass a videoId on the query string or in the   request body"
            };
        }
        context.done();
};

How can I return the JSON that fetchComments returns?

like image 391
Christian Gonzalez Avatar asked Mar 06 '23 22:03

Christian Gonzalez


1 Answers

Move assigning context.res and call to context.done to promise callback. Set Content-Type to application/json in the headers. Based on your code, something like

if (context.req.body.videoId =! null) {
  context.log('inicia a obtener comentarios')
  const fetchComments = require('youtube-comments-task')

  fetchComments(req.body.videoId)
    .fork(e => context.log('ERROR', e), p => {                   
       context.log('comments', p.comments);
       context.res = { 
         headers: { 'Content-Type': 'application/json' },
         body: p.comments 
       };
       context.done();
    });
}
else {
  context.res = {
    status: 400,
    body: "Please pass a videoId on the query string or in the request body"
  };
  context.done();
}
like image 173
Mikhail Shilkov Avatar answered Mar 10 '23 03:03

Mikhail Shilkov