JS-301-NodeServer
  • Introduction
  • js_library
    • Node Server
      • 00 - Intro
        • 01 - Purpose
        • 02 - Back-End Setup
        • 03 - Terms Cheat Sheet
      • 01 - Server Set up
        • 01 - npm packages
        • 02 - Express Intro
        • 03 - Express code
      • 02 - Development Tools
        • 01 - Nodemon Intro
        • 02 - Postman Intro
        • 03 - Postman set up
      • 03 - Routes Intro
        • 01 - Routes intro
        • 02 - Express Router() intro
        • 03 - Challenge 1
        • 04 - Challenge 2
      • 04 - Database Intro
        • 00 - DB Intro and Set up
          • 00 - DB Intro
          • 01 - PostgreSQL Intro
          • 02 - Install
        • 01 - Sequelize Intro
          • 01 - Sequelize intro
          • 02 - Initialize
      • 05 - Model View Controller
        • 01 - MVC
          • 00 - MVC Intro
        • 02 - Models
          • 01 - Intro to Models
          • 02 - Test Model
        • 03 - Controllers
          • 00 - Controllers Intro
          • 01 - Controller Set up
          • 02 - Create Method
          • 03 - req.body()
          • 04 - Crafting the Response
          • 05 - Sending the Response
          • 06 - JSON Response
          • 07 - Error Handling
        • 04 - Conclusion
      • 06 - Tokenization
        • 01 - JWT Intro
          • 01 - JWT intro
        • 02 - User Create
          • 01 - User Create
          • 02 - Refactor
        • 03 - User Token
          • 01 - JWT Package
          • 02 - Adding JWT
          • 03 - ENV
      • 07 - Encryption
        • 01 - bcrypt
        • 02 - bcrypt setup
      • 08 - Session
        • 00 - Session Intro
        • 01 - Sign In Method
        • 02 - Sign In Bcrypt
        • 03 - Sign In JWT
      • 09 - Middleware
        • 01 - Test Client HTML
        • 02 - Test Client JS
        • 03 - Middleware intro
        • 04 - Headers intro
        • 05 - Server Update
        • 06 - Test Post
        • 07 - Test Post Refactor
        • 08 - Post Data
        • 09 - Fetch From One
      • 10 - Authenticated Routes
        • 01 - Intro to Authenticated Routes
        • 02 - Validate Session
        • 03 - Changes to app.js
        • 04 - authtestcontroller.js
        • 05 - Delete an Item
        • 06 - Update an Item
        • 07 - Postman Testing
      • 11 - Authenticated Requests
        • 00 - Additions to index
        • 01 - Anatomy of a Request
        • 02 - Create User
        • 03 - Getting a Token
        • 04 - Get Items From One User
        • 05 - Creating an Item for a User
        • 06 - Get one item
        • 07 - Update an Item
        • 08 - Deleting an Item
        • 09 - Deleting with a Custom Event
      • 12 - Workout Log Server
        • 00 - Intro
      • 13 - More Sequelize Functions
        • Migrations
          • 00 - Intro
          • 01 - init and config
          • 02 - Creating the First Migration
          • 03 - Running Migrations
          • 04 - Reverting Migrations
          • 05 - Seeds
          • 06 - Reverting Seeds
        • Queries
          • 00 - Intro
          • 01 - Queries
Powered by GitBook
On this page
  • Overview
  • Code
  • Analysis
  • Test
  • Checking the Database
  • Summary of the Flow
  1. js_library
  2. Node Server
  3. 05 - Model View Controller
  4. 03 - Controllers

02 - Create Method

Previous01 - Controller Set upNext03 - req.body()

Last updated 7 years ago

In this module, we're going to create a second endpoint that accepts a POST with data, matches the request with a model, passes the data to Postgres, and sends a response.

Overview

Here's the flow of what we will have after this module:

Don't be overwhelemed. Notice that we've added usage of our model and our database.

Code

Now that we know a POST route works, let's add in our model and our database in another controller method. This time you'll need to import the test.js model. You'll put the next controller method underneath the first one inside testcontroller.js:

var express = require('express')
var router = express.Router()
var sequelize = require('../db');
var TestModel = sequelize.import('../models/test'); //1

/****************************************
 * Controller Method #1: Simple Response
****************************************/
router.post('/one', function(req, res){
  res.send("Got a post request.") 
});

/****************************************
 * Controller Method #2: Persisting Data
****************************************/
router.post('/two', function (req, res) {
  let testData = "Test data for endpoint two"; //2

  TestModel //3
    .create({ //4
        //6
      testdata: testData //5
    }).then(dataFromDatabase => {
        res.send("Test two went through!")
    })
});

module.exports = router;

Analysis

  1. We import the test model and store it in TestModel variable. It is convention to use Pascal casing (uppercase on both words) for a model class with Sequelize. You'll find this to be true in other programming languages as well.

  2. testData is going to have a fixed string that we'll use every time a POST request comes in.

  3. We use the TestModel variable to access the model that we are using. This will grant us access to the Test model properties and to Sequelize methods.

  4. .create() is a Sequelize method that allows us to create an instance of the Test model and send it off to the db, as long as the data types match the model.

  5. We pass the value of testData down to satisfy the key/value pair for the model. The string that we are sending will be the value that's stored in the variable. Currently, it is the string Test data for endpoint two;

  6. testdata is the key in the object, and it represents the column being used in the table.

Let's test this code in Postman and do some more work that should clarify this process.

Test

  1. Make sure your server is running.

  2. Open Postman.

  3. Open a new request.

  4. Change the dropdown to POST.

  5. Enter the endpoint into the URL: http://localhost:3000/test/two.

  6. Press 'Send'.

  7. You should see the following response:

Checking the Database

Guess what? We also should have just persisted our data to Postgres. Let's check using the following steps:

1. Open PGAdmin. (The elephant)

2. Find your workoutlog database.

3. Find Schemas dropdown.

4. Navigate your way to Tables.

5. You should see the tests table.

6. Right click on it, then click View Data -> View All Rows.

7. You should see the following. Note that we have underlined all of these steps in the image:

Summary of the Flow

In this module, the following flow is happening:

1. We make a POST request with Postman.

2. The router sends that request to the testcontroller.

3. The testcontroller method contains a variable called testData that has a string in it.

4. Our testcontroller method access the TestModel.

5. We then use the Sequelize create() method to create the object to be sent to the DB.

6. The object is sent and Postgres stores it.

7. The controller sends a response to Postman.

There is a lot going on now, but we still need to iterate and add more endpoints, routes, and controller steps to see how a full controller method should be built.

screenshot
screenshot
screenshot