Bootcamp
Search…
4.POCE.3: Project 2 MVC Refactor
We will use MVC to work to refactor your project into MVC.

Branch

Create a branch for this work called mvc.
Remember to change the syntax of the push command to git push origin mvc.

Refactor

The MVC architecture described in 4.3 should allow you to transfer over your app functionality one controller method (route) at a time.
Remember to try to rename things according to the table in 4.3.​
Don't write the Sequelize code right away.
The flow of work should be as follows:
  1. 1.
    Create the routes file.
  2. 2.
    If there is not an existing controller yet, create the controller file.
  3. 3.
    For a single route, create it in the routes file and create a method for it in the controller.
  4. 4.
    Create the appropriate view folder if it doesn't exist.
  5. 5.
    Create the view file.
Complete everything one controller at a time. Don't worry about completing a refactor of the entire app.
Some of your routes will not fit into a given DB table -> model -> controller paradigm, e.g. the logged in homepage, or another page that uses several models equally. Don't worry about that. You can put that route in whichever controller you choose, or you can also choose to make a controller especially for that page or set of pages.
When all the request callback code is transferred into the controller functions, begin work on the models.
  1. 1.
    If the model doesn't exist yet, create it.
  2. 2.
    Use the model in the controller.

pool.query Controller

You can still split the app into controllers without Sequelize.
Don't port your entire app over to Sequelize at once.
Begin by putting your routes into controllers.
In order to have access to pool.query in your controller, initialize it in routes.mjs and pass it into the controller:

index.mjs

1
import pg from 'pg';
2
import initItemsController from './controllers/items.mjs'
3
import db from './models/index.mjs';
4
​
5
const { Pool } = pg;
6
const poolConfig = {
7
user: process.env.USER,
8
host: 'localhost',
9
database: 'birding',
10
port: 5432,
11
};
12
const pool = new Pool(poolConfig);
13
​
14
export default function routes(app) {
15
​
16
// Where we init our controllers, we can also pass in pool.
17
const itemsController = initItemsController(db, pool);
18
​
19
// ...
Copied!
controllers/items.mjs
1
export default function items(db, pool) {
2
​
3
const index = (request, response) => {
4
​
5
pool.query('SELECT * FROM items', ( result ) => {
6
// ....
Copied!