qarly_blue
qarly_blue

Reputation: 420

Invoke AWS Lambda directly (without API Gateway) from Vuejs

I need invoke an AWS Lambda from my view in Vue.js without AWS API Gateway

Upvotes: 1

Views: 879

Answers (1)

qarly_blue
qarly_blue

Reputation: 420

First, include aws-sdk in you index.html (something like that):

nameproject/public/index.html

Include this src:

<script src="https://sdk.amazonaws.com/js/aws-sdk-2.866.0.min.js"></script>

Second, in your file.vue (something like that):

nameproject/src/views/myfile.vue

Include this code:

<script 
  import AWS from 'aws-sdk'
  const { Lambda } = require("@aws-sdk/client-lambda");


export default {
  props: {
  },
  computed: {
  },
  components: {
  },
  methods: {
    startCallBack: function() {
    },
    endCallBack: function() {
    },
    async invokeLambdaFunction(){
      var config = new AWS.Config({
        region: 'us-east-1',
        accessKeyId: '**YOUR_ACCESS_KEY**', 
        secretAccessKey: '**YOUR_SECRET_ACCESS_KEY**', 
      });

      var lambda_fun = new AWS.Lambda(config);
      var request = {
          "var_1" : "0",
          "var_2" : "1"
      };

      var pullParams = { 
        FunctionName : '**YOUR_FUNCTION_NAME**',
        InvocationType : 'RequestResponse',
        LogType: 'None',
        Payload: JSON.stringify(request)
      } 
      var pullResults;

      lambda_fun.invoke(pullParams, function (error, data) {
        if(error)
          console.log(error);
        else{
          pullResults = JSON.parse(data.Payload);
          console.log('returned result: ', JSON.stringify(pullResults, null, 2))
        }
      }
      )
    }
  },
  data() {
    return {
    };
  },
  created() {
    this.invokeLambdaFunction();
  }
};

</script>

Then you can see the response from Lambda.

Upvotes: 2

Related Questions