Skip to content

Instantly share code, notes, and snippets.

@saswata-dutta
Created August 7, 2023 19:37
Show Gist options
  • Save saswata-dutta/6a123f397a6bc2e8396557f6445ed231 to your computer and use it in GitHub Desktop.
Save saswata-dutta/6a123f397a6bc2e8396557f6445ed231 to your computer and use it in GitHub Desktop.

Revisions

  1. saswata-dutta created this gist Aug 7, 2023.
    74 changes: 74 additions & 0 deletions iam_rds_lambda.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@
    const { Signer } = require("@aws-sdk/rds-signer");
    const mysql = require("mysql2/promise");

    const headers = {
    "Content-Type": "application/json",
    };

    const rdsProps = {
    hostname: "???.???.ap-south-1.rds.amazonaws.com",
    port: 3306,
    username: "???",
    db: "???",
    region: "ap-south-1",
    };

    const signer = new Signer(rdsProps);

    // todo actual persistence query
    const sql = "select `rep_name`, `rep_email` from `accounts` where `id` = ? and `name` = ?";


    async function persist(args) {
    const connection = await mysql.createConnection({
    host: rdsProps.hostname,
    user: rdsProps.username,
    database: rdsProps.db,
    ssl: "Amazon RDS",
    connectTimeout: 5 * 1000,
    authPlugins: {
    mysql_clear_password: () => () => signer.getAuthToken(),
    }
    });

    // todo change to actual insert ignore query
    const [rows, meta] = await connection.execute(sql, args);
    return rows;
    }


    function sanitise(args) {
    // todo, throw if bad
    return args;
    }


    exports.handler = async (event, context) => {
    console.log("Event:", JSON.stringify(event, null, 2));

    let body;
    let statusCode = "200";
    try {
    switch (event.httpMethod) {
    case "POST":
    // vaildate api keys
    // todo extract args from event -> json of fields submitted
    body = await persist(sanitise([1,"foo"]));
    break;
    default:
    throw new Error(`Unsupported method "${event.httpMethod}"`);
    }
    } catch (err) {
    statusCode = "400";
    body = err.message;
    } finally {
    body = JSON.stringify(body);
    }

    // todo sent notification of successfully lead ingest
    return {
    statusCode,
    body,
    headers,
    };
    };