Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ Finally, in MySQL Workbench, run the `initialize.sql` script that is included in

## Overview

The routes/controllers and basic setup has been done for us. Our job is now to complete the queries in `controllers/users.js`. There are five different controller functions and the first one has been done for us. We should be able to see this by navigating to: http://localhost:4001/users/
The routes/controllers and basic setup has been done for us. Our job is now to complete the queries in `controllers/users.js`. There are five different controller functions and the first one has been done for us. We should be able to see this by navigating to: http://localhost:4001/users/

Keep in mind that your port (4001) may be different.

Take another look in the `sql/connections.js` file and notice how we set up the class to pass the same connection pool to any file that requests it.
Take another look in the `sql/connections.js` file and notice how we set up the class to pass the same connection pool to any file that requests it.

Additionally, navigate to the `initialize.sql` file and look at the CREATEs for the three tables. Do we notice anything different this time around? How about the `ON DELETE CASCADE` line? Remember last time when we couldn't delete a row from the users table because the usersContact and usersAddress were still dependent on it? That no longer applies with CASCADE. Now when we delete something from the users table it will automatically be deleted from the other two tables based on the foreign key relationship.
Additionally, navigate to the `initialize.sql` file and look at the CREATEs for the three tables. Do we notice anything different this time around? How about the `ON DELETE CASCADE` line? Remember last time when we couldn't delete a row from the users table because the usersContact and usersAddress were still dependent on it? That no longer applies with CASCADE. Now when we delete something from the users table it will automatically be deleted from the other two tables based on the foreign key relationship.

## Controller functions

Expand All @@ -47,7 +47,7 @@ Look at the following line where it says `mysql.format()`. What do you think goe

The route is going to look like this: http://localhost:4001/users/

We are going to need to use Postman to access this route since it is now a POST request.
We are going to need to use Postman to access this route since it is now a POST request.

We are going to send a body with the request that looks like this:

Expand All @@ -66,9 +66,9 @@ Again we will need to figure out what goes in the brackets

The route is going to look like this: http://localhost:4001/users/234

Which is similar to the GET about but this time it is a PUT. We will need to use Postman again to make this work.
Which is similar to the GET about but this time it is a PUT. We will need to use Postman again to make this work.

The goal of this route is to again send a body and this time change the first_name and last_name fields for the row that matches that id. The body for this request will remain the same as last time:
The goal of this route is to again send a body and this time change the first_name and last_name fields for the row that matches that id. The body for this request will remain the same as last time:

```
{
Expand All @@ -90,8 +90,8 @@ Write a SQL statement to DELETE FROM users WHERE first_name = req param first_na
### Create a full Query

- In your `getAllUsers` return all fields of all users including the fields of `usersContact` & `usersAddress`
- In your `createUser` be sure that a complete user is created inluding all fields in `usersContact` & `usersAddress`
- In your `createUser` be sure that a complete user is created including all fields in `usersContact` & `usersAddress`

## Summary

If all went according to plan we now have a full CRUD API that selects, inserts, updates and deletes from a SQL database. Great job! Take the time to start expanding on these concepts.
If all went according to plan we now have a full CRUD API that selects, inserts, updates and deletes from a SQL database. Great job! Take the time to start expanding on these concepts.
66 changes: 36 additions & 30 deletions controllers/users.js
Original file line number Diff line number Diff line change
@@ -1,67 +1,73 @@
const mysql = require('mysql')
const pool = require('../sql/connection')
const { handleSQLError } = require('../sql/error')
const mysql = require("mysql");
const pool = require("../sql/connection");
const { handleSQLError } = require("../sql/error");

const getAllUsers = (req, res) => {
// SELECT ALL USERS
pool.query("SELECT * FROM users", (err, rows) => {
if (err) return handleSQLError(res, err)
let sql =
"SELECT * FROM users JOIN usersAddress on users.id = usersAddress.user_id JOIN usersContact on users.id = usersContact.user_id";
pool.query(sql, (err, rows) => {
if (err) return handleSQLError(res, err);
return res.json(rows);
})
}
});
};

const getUserById = (req, res) => {
// SELECT USERS WHERE ID = <REQ PARAMS ID>
let sql = "QUERY GOES HERE"
let sql = "SELECT * FROM users WHERE ?? = ?";
// WHAT GOES IN THE BRACKETS
sql = mysql.format(sql, [])
sql = mysql.format(sql, ["id", `${req.params.id}`]);

pool.query(sql, (err, rows) => {
if (err) return handleSQLError(res, err)
if (err) return handleSQLError(res, err);
return res.json(rows);
})
}
});
};

const createUser = (req, res) => {
// INSERT INTO USERS FIRST AND LAST NAME
let sql = "QUERY GOES HERE"
// INSERT INTO USERS FIRST AND LAST NAME
let sql = "INSERT INTO users (first_name, last_name) VALUES (?, ?)";
// WHAT GOES IN THE BRACKETS
sql = mysql.format(sql, [])
sql = mysql.format(sql, [req.body.first_name, req.body.last_name]);

pool.query(sql, (err, results) => {
if (err) return handleSQLError(res, err)
if (err) return handleSQLError(res, err);
return res.json({ newId: results.insertId });
})
}
});
};

const updateUserById = (req, res) => {
// UPDATE USERS AND SET FIRST AND LAST NAME WHERE ID = <REQ PARAMS ID>
let sql = ""
let sql = "UPDATE users SET first_name = ?, last_name = ? WHERE id = ?";
// WHAT GOES IN THE BRACKETS
sql = mysql.format(sql, [])
sql = mysql.format(sql, [
req.body.first_name,
req.body.last_name,
req.params.id,
]);

pool.query(sql, (err, results) => {
if (err) return handleSQLError(res, err)
if (err) return handleSQLError(res, err);
return res.status(204).json();
})
}
});
};

const deleteUserByFirstName = (req, res) => {
// DELETE FROM USERS WHERE FIRST NAME = <REQ PARAMS FIRST_NAME>
let sql = ""
let sql = "DELETE FROM users WHERE first_name = ?";
// WHAT GOES IN THE BRACKETS
sql = mysql.format(sql, [])
sql = mysql.format(sql, [req.params.first_name]);

pool.query(sql, (err, results) => {
if (err) return handleSQLError(res, err)
if (err) return handleSQLError(res, err);
return res.json({ message: `Deleted ${results.affectedRows} user(s)` });
})
}
});
};

module.exports = {
getAllUsers,
getUserById,
createUser,
updateUserById,
deleteUserByFirstName
}
deleteUserByFirstName,
};
14 changes: 7 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
const express = require("express");
const bodyParser = require("body-parser");
const usersRouter = require('./routers/users');
const usersRouter = require("./routers/users");

const app = express();
const port = process.env.PORT || 4001;

app.use(bodyParser.json())
app.use('/users', usersRouter)
app.use(bodyParser.json());
app.use("/users", usersRouter);

app.get('/', (req, res) => {
res.send('Welcome to our server!')
})
app.get("/", (req, res) => {
res.send("Welcome to our server!");
});

app.listen(port, () => {
console.log(`Web server is listening on port ${port}!`);
console.log(`Web server is listening on port ${port}!`);
});
Loading