genkio / blog

Stay hungry stay foolish
https://slashbit.github.io/blog/
0 stars 1 forks source link

AWS Lambda recipes #146

Open genkio opened 7 years ago

genkio commented 7 years ago

Passing information through API Gateway

source

Configure API Gateway

  1. Go to API Gateway > APIs > Resources > Integration Request > Body Mapping Templates

  2. Create a new body mapping templates with content-type application/json

    {
    "min": $input.params('min'),
    "max": $input.params('max')
    // to accept json: $input.json('$.message')
    }
  3. Re-deploy API in the Resources > Actions menu

To get input params in the event object

'use strict';

// simple random number generator
exports.handler = (event, context, callback) => {
  let min = event.min;
  let max = event.max;

  let generatedNumber = Math.floor(Math.random() * max) + min;
  callback(null, generatedNumber);
};

Using scheduled events to trigger lambda function

source

'use strict';

exports.handler = (event, context, callback) => {
  const api_key = process.env.apiKey;
  const domain = process.env.domain;
  const mailgun = require('mailgun-js')({ apiKey: api_key, domain: domain });

  let data = {
    from: 'Lambda <from@example.com>',
    to: 'to@example.com',
    subject: 'Hello',
    text: 'Hello from Lambda'
  };

  mailgun.messages().send(data, (error, body) => {
    callback(error, body);
  })
};

Configure CloudWatch

  1. Create a new scheduled CloudWatch rule at CloudWatch Dashboard > Rules
  2. Create Rule with cron expression 36 19 * * ? * (after 36 minutes, 19 hours every day)
  3. Select lambda function as Target

Writing data to DynamoDB

source

'use strict';

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'eu-west-1'});

exports.handler = (event, context, callback) => {
  let params = {
    Item: {
      date: Date.now(),
      message: "Awesome message board!"
    },
    TableName: 'guestbook'
  };

  docClient.put(params, (error, data) => {
    if (error) {
      callback(error);
    } else {
      callback(null, data);
    }
  });
};

Create a new Inline Policy for the dynamodb_lambda_function role (which is assigned to our sample lambda function) with these settings:

Querying DynamoDB with lambda

source

'use strict';

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'eu-west-1'});

exports.handler = (event, context, callback) => { 
  let scanningParameters = {
    TableName: 'guestbook',
    Limit: 100    
  };

  // approach #1 by using scan
  // be aware, scan is expensive as it loops through all records
  docClient.scan(scanningParameters, (error, data) => { 
    if (error) {
      callback(error);
    } else {
      callback(null, data);
    }
  });

  /*
  // approach #2 by using query
  // you can only query the primary key, and sort the secondary key
  let params = {
    TableName: 'guestbook',
    Key: {
      'date': 1491013689483
    }
  };

  docClient.get(params, (error, data) => {
    if (error) {
      callback(error);
    } else {
      callback(null, data);
    }
  });
  */
};

Enable CORS for your Resources

By go to Resources > Actions > Enable CORS, and set Access-Control-Allow-Origin to either origin domain or '*' (for testing purpose only)

Implementing a dead simple front-end to interact with Lambda

source

<div id="entries"></div>
<form>
  <textarea id="msg"></textarea>
  <button id="submitBtn">Submit</button>
</form>
var API_URL = 'resources_url';

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    url: API_URL,
    success: function(data) {
      $('#entries').html('');
      data.Items.forEach(function(item) {
        $('#entries').append('<p>' + item.message + '</p>');
      });
    }
  });

  $('#submitBtn').on('click', function() {
    $.ajax({
      type: 'POST',
      url: API_URL,
      data: JSON.stringify({ 'message': $('#msg').val() }),
      contentType: 'application/json',
      success: function(data) {
        location.reload();
      }
    });

    return false;
  });
});