lambda with graphql and sqs send 2 messages to sqs in nodejs?












0














i'm working on project where i need to write a lambda function which provides AWS API to handles GraphQL query and send the payload to AWS SQS everything is working fine but when i check my AWS SQS queue it shows 2 messages every single time instead of 1 and cloud watch also shows function trigger only once. below i'm sharing my code with you any help would be very much appreciated.



index.js



const { graphql } = require("graphql");
const { schema } = require("./graphql/schema");

exports.handler = async (event) => {
// getting query from lambda event
const query = event.query;

// getting query variables from lambda event
const variables = event.variables;

return await graphql(schema, query, null, null, variables);
};


sqs.js



const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1"});

// Create an SQS service object
const sqs = new AWS.SQS({apiVersion: '2012-11-05', "accessKeyId": process.env.ACCESS_KEY_ID, "secretAccessKey": process.env.SECRET_ACCESS_KEY});
const QueueUrl = process.env.SQS_QUEUE_URL;

const sendPayloadToSQS = message => {
const params = {
MessageBody: JSON.stringify(message),
QueueUrl
};

await sqs.sendMessage(params, function(err, data) {
if (err) {
console.log("Message sending failed : ", err);
} else {
console.log("Message queued to SQS successfully : ", data.MessageId);
}
}).promise();

};

module.exports = sendPayloadToSQS;


graphql mutation file



const { GraphQLNonNull } = require("graphql");
const { mutationWithClientMutationId } = require("../../common");
const { JobRequestEventResponse } = require("../jobRequestEventResponse");
const { JobRequestInput, JobEventMetadataInput } = require("../jobSchema");
const sendPayloadToSQS = require("../../../sqs");
const { newId } = require("../../../newId");

const JobRequestEvent = mutationWithClientMutationId({
name: "JobRequestEvent",
inputFields: {
eventMetadataInput: {
type: new GraphQLNonNull(JobEventMetadataInput),
},
eventInput: {
type: new GraphQLNonNull(JobRequestInput),
},
},
outputFields: {
JobRequestEventResponse: {
type: JobRequestEventResponse,
},
},
mutateAndGetPayload: async (params) => {
const new_id = newId();
if(params.eventInput.jobId === null || params.eventInput.jobId === undefined) {
params.eventInput.jobId = new_id;
}
const payload = {
_id: new_id,
transactionId: new_id,
name: params.eventMetadataInput.name,
userRole: params.eventMetadataInput.userRole,
date: params.eventMetadataInput.date,
languageCode: params.eventMetadataInput.languageCode,
eventInput: params.eventInput,
};

//send payload to sqs
await sendPayloadToSQS(payload);

return {
JobRequestEventResponse: {
id: payload._id,
transactionId: payload.transactionId,
status: "Success",
},
};
},
});

module.exports = {
JobRequestEvent,
};









share|improve this question



























    0














    i'm working on project where i need to write a lambda function which provides AWS API to handles GraphQL query and send the payload to AWS SQS everything is working fine but when i check my AWS SQS queue it shows 2 messages every single time instead of 1 and cloud watch also shows function trigger only once. below i'm sharing my code with you any help would be very much appreciated.



    index.js



    const { graphql } = require("graphql");
    const { schema } = require("./graphql/schema");

    exports.handler = async (event) => {
    // getting query from lambda event
    const query = event.query;

    // getting query variables from lambda event
    const variables = event.variables;

    return await graphql(schema, query, null, null, variables);
    };


    sqs.js



    const AWS = require("aws-sdk");
    AWS.config.update({ region: "us-east-1"});

    // Create an SQS service object
    const sqs = new AWS.SQS({apiVersion: '2012-11-05', "accessKeyId": process.env.ACCESS_KEY_ID, "secretAccessKey": process.env.SECRET_ACCESS_KEY});
    const QueueUrl = process.env.SQS_QUEUE_URL;

    const sendPayloadToSQS = message => {
    const params = {
    MessageBody: JSON.stringify(message),
    QueueUrl
    };

    await sqs.sendMessage(params, function(err, data) {
    if (err) {
    console.log("Message sending failed : ", err);
    } else {
    console.log("Message queued to SQS successfully : ", data.MessageId);
    }
    }).promise();

    };

    module.exports = sendPayloadToSQS;


    graphql mutation file



    const { GraphQLNonNull } = require("graphql");
    const { mutationWithClientMutationId } = require("../../common");
    const { JobRequestEventResponse } = require("../jobRequestEventResponse");
    const { JobRequestInput, JobEventMetadataInput } = require("../jobSchema");
    const sendPayloadToSQS = require("../../../sqs");
    const { newId } = require("../../../newId");

    const JobRequestEvent = mutationWithClientMutationId({
    name: "JobRequestEvent",
    inputFields: {
    eventMetadataInput: {
    type: new GraphQLNonNull(JobEventMetadataInput),
    },
    eventInput: {
    type: new GraphQLNonNull(JobRequestInput),
    },
    },
    outputFields: {
    JobRequestEventResponse: {
    type: JobRequestEventResponse,
    },
    },
    mutateAndGetPayload: async (params) => {
    const new_id = newId();
    if(params.eventInput.jobId === null || params.eventInput.jobId === undefined) {
    params.eventInput.jobId = new_id;
    }
    const payload = {
    _id: new_id,
    transactionId: new_id,
    name: params.eventMetadataInput.name,
    userRole: params.eventMetadataInput.userRole,
    date: params.eventMetadataInput.date,
    languageCode: params.eventMetadataInput.languageCode,
    eventInput: params.eventInput,
    };

    //send payload to sqs
    await sendPayloadToSQS(payload);

    return {
    JobRequestEventResponse: {
    id: payload._id,
    transactionId: payload.transactionId,
    status: "Success",
    },
    };
    },
    });

    module.exports = {
    JobRequestEvent,
    };









    share|improve this question

























      0












      0








      0







      i'm working on project where i need to write a lambda function which provides AWS API to handles GraphQL query and send the payload to AWS SQS everything is working fine but when i check my AWS SQS queue it shows 2 messages every single time instead of 1 and cloud watch also shows function trigger only once. below i'm sharing my code with you any help would be very much appreciated.



      index.js



      const { graphql } = require("graphql");
      const { schema } = require("./graphql/schema");

      exports.handler = async (event) => {
      // getting query from lambda event
      const query = event.query;

      // getting query variables from lambda event
      const variables = event.variables;

      return await graphql(schema, query, null, null, variables);
      };


      sqs.js



      const AWS = require("aws-sdk");
      AWS.config.update({ region: "us-east-1"});

      // Create an SQS service object
      const sqs = new AWS.SQS({apiVersion: '2012-11-05', "accessKeyId": process.env.ACCESS_KEY_ID, "secretAccessKey": process.env.SECRET_ACCESS_KEY});
      const QueueUrl = process.env.SQS_QUEUE_URL;

      const sendPayloadToSQS = message => {
      const params = {
      MessageBody: JSON.stringify(message),
      QueueUrl
      };

      await sqs.sendMessage(params, function(err, data) {
      if (err) {
      console.log("Message sending failed : ", err);
      } else {
      console.log("Message queued to SQS successfully : ", data.MessageId);
      }
      }).promise();

      };

      module.exports = sendPayloadToSQS;


      graphql mutation file



      const { GraphQLNonNull } = require("graphql");
      const { mutationWithClientMutationId } = require("../../common");
      const { JobRequestEventResponse } = require("../jobRequestEventResponse");
      const { JobRequestInput, JobEventMetadataInput } = require("../jobSchema");
      const sendPayloadToSQS = require("../../../sqs");
      const { newId } = require("../../../newId");

      const JobRequestEvent = mutationWithClientMutationId({
      name: "JobRequestEvent",
      inputFields: {
      eventMetadataInput: {
      type: new GraphQLNonNull(JobEventMetadataInput),
      },
      eventInput: {
      type: new GraphQLNonNull(JobRequestInput),
      },
      },
      outputFields: {
      JobRequestEventResponse: {
      type: JobRequestEventResponse,
      },
      },
      mutateAndGetPayload: async (params) => {
      const new_id = newId();
      if(params.eventInput.jobId === null || params.eventInput.jobId === undefined) {
      params.eventInput.jobId = new_id;
      }
      const payload = {
      _id: new_id,
      transactionId: new_id,
      name: params.eventMetadataInput.name,
      userRole: params.eventMetadataInput.userRole,
      date: params.eventMetadataInput.date,
      languageCode: params.eventMetadataInput.languageCode,
      eventInput: params.eventInput,
      };

      //send payload to sqs
      await sendPayloadToSQS(payload);

      return {
      JobRequestEventResponse: {
      id: payload._id,
      transactionId: payload.transactionId,
      status: "Success",
      },
      };
      },
      });

      module.exports = {
      JobRequestEvent,
      };









      share|improve this question













      i'm working on project where i need to write a lambda function which provides AWS API to handles GraphQL query and send the payload to AWS SQS everything is working fine but when i check my AWS SQS queue it shows 2 messages every single time instead of 1 and cloud watch also shows function trigger only once. below i'm sharing my code with you any help would be very much appreciated.



      index.js



      const { graphql } = require("graphql");
      const { schema } = require("./graphql/schema");

      exports.handler = async (event) => {
      // getting query from lambda event
      const query = event.query;

      // getting query variables from lambda event
      const variables = event.variables;

      return await graphql(schema, query, null, null, variables);
      };


      sqs.js



      const AWS = require("aws-sdk");
      AWS.config.update({ region: "us-east-1"});

      // Create an SQS service object
      const sqs = new AWS.SQS({apiVersion: '2012-11-05', "accessKeyId": process.env.ACCESS_KEY_ID, "secretAccessKey": process.env.SECRET_ACCESS_KEY});
      const QueueUrl = process.env.SQS_QUEUE_URL;

      const sendPayloadToSQS = message => {
      const params = {
      MessageBody: JSON.stringify(message),
      QueueUrl
      };

      await sqs.sendMessage(params, function(err, data) {
      if (err) {
      console.log("Message sending failed : ", err);
      } else {
      console.log("Message queued to SQS successfully : ", data.MessageId);
      }
      }).promise();

      };

      module.exports = sendPayloadToSQS;


      graphql mutation file



      const { GraphQLNonNull } = require("graphql");
      const { mutationWithClientMutationId } = require("../../common");
      const { JobRequestEventResponse } = require("../jobRequestEventResponse");
      const { JobRequestInput, JobEventMetadataInput } = require("../jobSchema");
      const sendPayloadToSQS = require("../../../sqs");
      const { newId } = require("../../../newId");

      const JobRequestEvent = mutationWithClientMutationId({
      name: "JobRequestEvent",
      inputFields: {
      eventMetadataInput: {
      type: new GraphQLNonNull(JobEventMetadataInput),
      },
      eventInput: {
      type: new GraphQLNonNull(JobRequestInput),
      },
      },
      outputFields: {
      JobRequestEventResponse: {
      type: JobRequestEventResponse,
      },
      },
      mutateAndGetPayload: async (params) => {
      const new_id = newId();
      if(params.eventInput.jobId === null || params.eventInput.jobId === undefined) {
      params.eventInput.jobId = new_id;
      }
      const payload = {
      _id: new_id,
      transactionId: new_id,
      name: params.eventMetadataInput.name,
      userRole: params.eventMetadataInput.userRole,
      date: params.eventMetadataInput.date,
      languageCode: params.eventMetadataInput.languageCode,
      eventInput: params.eventInput,
      };

      //send payload to sqs
      await sendPayloadToSQS(payload);

      return {
      JobRequestEventResponse: {
      id: payload._id,
      transactionId: payload.transactionId,
      status: "Success",
      },
      };
      },
      });

      module.exports = {
      JobRequestEvent,
      };






      node.js amazon-web-services graphql amazon-sqs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 27 at 13:58









      Ankur Dubey

      45




      45
























          1 Answer
          1






          active

          oldest

          votes


















          -1














          I read the documentation again and found the callback is the root cause of my problem: if I provide a callback to sendMessage it triggers my function and after when I write promise() again it triggers my function so I remove the callback only as you can see below.



          Refer : AWS Official documentation



          Instead of this:



          await sqs.sendMessage(params, function(err, data) {
          if (err) {
          console.log("Message sending failed : ", err);
          } else {
          console.log("Message queued to SQS successfully : ", data.MessageId);
          }
          }).promise();


          I write this:



          const request = sqs.sendMessage(params);
          const result = await request.promise();

          if(result) {
          console.log("Message queued to SQS successfully : ", result.MessageId);
          } else {
          console.log("Message queued failed");
          }





          share|improve this answer























          • Please add the solution here rather than writing the thanks message.
            – Shivang Agarwal
            Dec 28 at 6:17











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946284%2flambda-with-graphql-and-sqs-send-2-messages-to-sqs-in-nodejs%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          -1














          I read the documentation again and found the callback is the root cause of my problem: if I provide a callback to sendMessage it triggers my function and after when I write promise() again it triggers my function so I remove the callback only as you can see below.



          Refer : AWS Official documentation



          Instead of this:



          await sqs.sendMessage(params, function(err, data) {
          if (err) {
          console.log("Message sending failed : ", err);
          } else {
          console.log("Message queued to SQS successfully : ", data.MessageId);
          }
          }).promise();


          I write this:



          const request = sqs.sendMessage(params);
          const result = await request.promise();

          if(result) {
          console.log("Message queued to SQS successfully : ", result.MessageId);
          } else {
          console.log("Message queued failed");
          }





          share|improve this answer























          • Please add the solution here rather than writing the thanks message.
            – Shivang Agarwal
            Dec 28 at 6:17
















          -1














          I read the documentation again and found the callback is the root cause of my problem: if I provide a callback to sendMessage it triggers my function and after when I write promise() again it triggers my function so I remove the callback only as you can see below.



          Refer : AWS Official documentation



          Instead of this:



          await sqs.sendMessage(params, function(err, data) {
          if (err) {
          console.log("Message sending failed : ", err);
          } else {
          console.log("Message queued to SQS successfully : ", data.MessageId);
          }
          }).promise();


          I write this:



          const request = sqs.sendMessage(params);
          const result = await request.promise();

          if(result) {
          console.log("Message queued to SQS successfully : ", result.MessageId);
          } else {
          console.log("Message queued failed");
          }





          share|improve this answer























          • Please add the solution here rather than writing the thanks message.
            – Shivang Agarwal
            Dec 28 at 6:17














          -1












          -1








          -1






          I read the documentation again and found the callback is the root cause of my problem: if I provide a callback to sendMessage it triggers my function and after when I write promise() again it triggers my function so I remove the callback only as you can see below.



          Refer : AWS Official documentation



          Instead of this:



          await sqs.sendMessage(params, function(err, data) {
          if (err) {
          console.log("Message sending failed : ", err);
          } else {
          console.log("Message queued to SQS successfully : ", data.MessageId);
          }
          }).promise();


          I write this:



          const request = sqs.sendMessage(params);
          const result = await request.promise();

          if(result) {
          console.log("Message queued to SQS successfully : ", result.MessageId);
          } else {
          console.log("Message queued failed");
          }





          share|improve this answer














          I read the documentation again and found the callback is the root cause of my problem: if I provide a callback to sendMessage it triggers my function and after when I write promise() again it triggers my function so I remove the callback only as you can see below.



          Refer : AWS Official documentation



          Instead of this:



          await sqs.sendMessage(params, function(err, data) {
          if (err) {
          console.log("Message sending failed : ", err);
          } else {
          console.log("Message queued to SQS successfully : ", data.MessageId);
          }
          }).promise();


          I write this:



          const request = sqs.sendMessage(params);
          const result = await request.promise();

          if(result) {
          console.log("Message queued to SQS successfully : ", result.MessageId);
          } else {
          console.log("Message queued failed");
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 28 at 11:04









          E_net4 wishes happy holidays

          11.9k63468




          11.9k63468










          answered Dec 28 at 5:35









          Ankur Dubey

          45




          45












          • Please add the solution here rather than writing the thanks message.
            – Shivang Agarwal
            Dec 28 at 6:17


















          • Please add the solution here rather than writing the thanks message.
            – Shivang Agarwal
            Dec 28 at 6:17
















          Please add the solution here rather than writing the thanks message.
          – Shivang Agarwal
          Dec 28 at 6:17




          Please add the solution here rather than writing the thanks message.
          – Shivang Agarwal
          Dec 28 at 6:17


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946284%2flambda-with-graphql-and-sqs-send-2-messages-to-sqs-in-nodejs%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas