Coder Social home page Coder Social logo

elijahrich1113 / aws-rds-demo Goto Github PK

View Code? Open in Web Editor NEW

This project forked from junior-devleague/aws-rds-demo

0.0 1.0 0.0 36 KB

[Advanced] - Connecting to AWS RDS PostgreSQL instance and creating CRUD Operations

JavaScript 90.24% HTML 9.76%

aws-rds-demo's Introduction

AWS RDS Demo

What is AWS RDS

A service that allows you to set up and operate a relational database in the cloud. It allows us to create a PostgreSQL instance

Flow of Data

Data Flow

Postgres Setup

  1. Connect to AWS RDS Postgres shell
psql --host instanceendpoint --port 5432 --username username --dbname dbname
  1. Ask your instructor for the user password
  2. Create user with encrypted password
  3. Grant user to jrdevleague
GRANT your_user TO "jrDevleague";
  1. Create database named hta-YOUR_NAME with newly created user
  2. Connect into newly created database
  3. Create table student with the following columns
  • student_id
  • name
  • grade_level
  1. Insert data for one student
  2. Grant table privileges to user
GRANT ALL PRIVILEGES ON TABLE YOUR_TABLE_NAME TO YOUR_USERNAME;

Serverless Setup

  1. Create serverless boilerplate/template
  2. Change service to aws-rds-demo-YOURNAMEin your serverless.yml
  3. Create a routes folder
  4. Add iamRoleStatements to allows rds in your serveless.yml
iamRoleStatements:
  - Effect: Allow
    Action:
      - rds:*
    Resource: "*"
  1. Create a GET lambda function in routes folder
  • set up your http method
  • set up your http path
  • set up your cors

6.npm install pg pg-pool 7. Create config.json file with the following:

{
  "table": "YOUR_TABLE_NAME",
  "host": "jrdevleague.cb9co1xxtizk.us-west-2.rds.amazonaws.com",
  "database": "YOUR_DATABASE_NAME",
  "user": "YOUR_USERNAME",
  "password": "YOUR_PASSWORD",
  "port": 5432
}
  1. Add config.json to your .gitignore

Get Lambda Function

  1. Require pg-pool
const Pool =  require('pg-pool');
  1. Require config file
const config =  require('../config.json')
  1. Use ES6 Object Destructuring to grab keys/properties from config.json
const { table, host, database, user, password, port } = config
  1. Create new pool object
const pool =  new  Pool({
  host,
  database,
  user,
  password,
  port,
  idleTimeoutMillis: 1000
});
  1. Create a SELECT query and save it into a variable
const getAllMovies =  "SELECT * FROM " + table +  ";";
  1. Use pool.connect() to connect to database
  2. Within the response use client.release() to open up database for query
  3. Run return client.query(YOUR_QUERY) to make your query
  4. Your get function should look like the following:
module.exports.get = (event, context, callback) => {

  const getAllStudents = "SELECT * FROM " + table + ";";

  pool.connect()
    .then(client => {
      client.release()
      return client.query(getAllStudents)
    })
    .then(res => {

      const response = {
        statusCode: 200,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Credentials": true
        },
        body: JSON.stringify(res.rows),
      }

      callback(null, response);
    })
    .catch(error => {
      console.log('error', error)

      const response = {
        statusCode: 500,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Credentials": true
        },
        body: JSON.stringify(error)
      }
      callback(null, response);
    });
};
  1. Invoke function or run GET endpoint in Postman

POST Lambda Function

  1. Allow permission to your table name
GRANT USAGE, SELECT ON SEQUENCE TABLE_NAME_id_seq TO YOUR_USERNAME;
  1. Add integration: lambda under cors: true of your post function in serverless.yml
  2. Create insert query
const postStudent =  "INSERT INTO " + table +  " Values(default, $1, $2)"
  1. Pass in values within pool.connect() code block with the following
return client.query(postStudent, \[name, grade_level\])
  1. Your post function should look like the following:
module.exports.post = (event, context, callback) => {
    let { name, grade_level } = event.body

    const postStudent = "INSERT INTO " + table + " Values(default, $1, $2)"

    pool.connect()
        .then((client) => {
            client.release()
            return client.query(postStudent, [name, grade_level])
        })
        .then((res) => {
            const response = {
                statusCode: 200,
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Credentials": true
                },
                body: JSON.stringify(res)
            }
            callback(null, response);
            console.log('Your connection will now be terminated')
        })
        .catch(e => {
            console.log('error', e)
            const response = {
                "statusCode": 500,
                "body": JSON.stringify(e)
            }
            callback(null, response);
        });
};

Class Exercise

  • Implement Put & Delete functions

Update Query Documentation

PostgreSQL: Documentation: 11: DELETE

Resources

What Is Amazon Relational Database Service (Amazon RDS)? - Amazon Relational Database Service

pg-pool

aws-rds-demo's People

Contributors

jaygiang avatar elijahrich1113 avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.