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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,29 @@ Your assignment page on Canvas should contain instructions for submitting this p
Visit [SQL Try Editor at W3Schools.com](https://www.w3schools.com/Sql/trysql.asp?filename=trysql_select_all) using Chrome and build the queries below. Once they work copy them to the `queries.sql` file at the root of the project.

- Find all customers with postal code 1010. Returns 3 records.
SELECT customername, postalcode FROM [Customers]
where postalcode = 1010

- Find the phone number for the supplier with the id 11. Should be (010) 9984510.
SELECT phone, suppliername FROM [Suppliers]
where supplierid = 11

- List first 10 orders placed, sorted descending by the order date. The order with date 1997-02-12 should be at the top.
SELECT * FROM [Orders]
order by orderdate desc limit 10

- Find all customers that live in London, Madrid, or Brazil. Returns 18 records.
SELECT customername, city, country FROM [Customers]
where city = "London" or city = "Madrid" or country = "Brazil"

- Add a customer record for _"The Shire"_, the contact name is _"Bilbo Baggins"_ the address is _"1 Hobbit-Hole"_ in _"Bag End"_, postal code _"111"_ and the country is _"Middle Earth"_.
insert into [Customers](CustomerName, ContactName, Address, City, PostalCode, Country)
values("The Shire", "Bilbo Baggins", "1 Hobbit-Hole", "Bag End", "111", "Middle Earth")

- Update _Bilbo Baggins_ record so that the postal code changes to _"11122"_.
update [Customers]
set PostalCode = 11122
where PostalCode = 111

**Clicking the `Restore Database` button in the page will repopulate the database with the original data and discard all changes you have made**.

Expand Down
61 changes: 59 additions & 2 deletions api/accounts/accounts-middleware.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,70 @@
// Bring in Model
const Account = require('./accounts-model')
// Bringing in this idk why
const db = require('../../data/db-config')

exports.checkAccountPayload = (req, res, next) => {
// DO YOUR MAGIC
// Note: you can either write "manual" validation logic
// or use the Yup library (not currently installed)

// console.log('checkAccountPayload middleware')
// next()

// - `checkAccountPayload` returns a status 400 with if `req.body` is invalid:
// - If either name or budget are undefined, return `{ message: "name and budget are required" }` - ok
// - If the _trimmed_ name is shorter than 3 or longer than 100, return `{ message: "name of account must be between 3 and 100" }` - ok
// - If budget is not able to be converted into a number, return `{ message: "budget of account must be a number" }` - ok
// - If budget is a negative number or over one million, return `{ message: "budget of account is too large or too small" }` - ok

// const error = { status: 400 }
const { name, budget } = req.body
if (name === undefined || budget === undefined) {
return res.status(400).json({message: 'name and budget are required'})
} else if (name.trim().length < 3 || name.trim().length > 100) {
return res.status(400).json({message: 'name of account must be between 3 and 100'})
} else if (typeof budget !== 'number' || isNaN(budget )) {
return res.status(400).json({message:'budget of account must be a number' })

} else if (budget < 0 || budget > 1000) {
return res.status(400).json({message:'budget of account is too large or too small' })
}
next()

}

exports.checkAccountNameUnique = (req, res, next) => {
exports.checkAccountNameUnique = async (req, res, next) => {
// DO YOUR MAGIC
//console.log('checkAccountNameUnique middleware')
//next()

// returns a status 400 with a `{ message: "that name is taken" }` if the _trimmed_ `req.body.name` already exists in the database
try {
const existing = await db('accounts')
.where('name', req.body.name.trim())
.first()

if (existing) {
next({ status: 400, messae: 'that name is taken'})
} else {
next()
}
} catch (err) {
next(err)
}
}

exports.checkAccountId = (req, res, next) => {
exports.checkAccountId = async (req, res, next) => {
// DO YOUR MAGIC
try {
const account = await Account.getById(req.params.id)
if (!account) {
next({ status: 404, message: 'account not found' })
} else {
req.account = account
next()
}
} catch(err) {
next(err)
}
}
17 changes: 15 additions & 2 deletions api/accounts/accounts-model.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
// Bring in db
const db = require('../../data/db-config')

const getAll = () => {
// DO YOUR MAGIC
// select * from accounts;
return db('accounts');
}

const getById = id => {
// DO YOUR MAGIC
// select * from accounts where id = 1;
return db('accounts').where('id', id).first()
}

const create = account => {
const create = async account => {
// DO YOUR MAGIC
const [id] = await db('accounts').insert(account)
return getById(id)
}

const updateById = (id, account) => {
const updateById = async (id, account) => {
// DO YOUR MAGIC
await db('accounts').where('id', id).update(account)
return getById(id)
}

const deleteById = id => {
// DO YOUR MAGIC
// delete from account whee id = 1
return db('accounts').where('id', id).del()
}

module.exports = {
Expand Down
61 changes: 56 additions & 5 deletions api/accounts/accounts-router.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,78 @@
const router = require('express').Router()
// Pull in Middleware
const md = require('./accounts-middleware')
// Pull in Accounts Model
const Account = require('./accounts-model')

router.get('/', (req, res, next) => {
router.get('/', async (req, res, next) => {
// DO YOUR MAGIC
try {
const accounts = await Account.getAll()
res.json(accounts)
} catch(err) {
next(err)
}
})

router.get('/:id', (req, res, next) => {
router.get('/:id', md.checkAccountId, async (req, res, next) => {
// DO YOUR MAGIC
res.json(req.account)
})

router.post('/', (req, res, next) => {
// create
router.post('/',
md.checkAccountPayload,
async (req, res, next) => {
// DO YOUR MAGIC
try {
//const name = await Account.
const newAccount = await Account.create({
name: req.body.name.trim(),
budget: req.body.budget,
})
res.status(201).json(newAccount)
} catch(err) {
next(err)
}
})

router.put('/:id', (req, res, next) => {
// update
router.put('/:id',
md.checkAccountPayload,
async (req, res, next) => {
// DO YOUR MAGIC
try {
const exists = await Account.getById(req.params.id)
// console.log(exists)
if (!exists) {

return res.status(404).json({message: 'id does not exist'})
}
const updated = await Account.updateById(req.params.id, req.body)

res.json(updated)
} catch(err) {
next(err)
}
});

router.delete('/:id', (req, res, next) => {
router.delete('/:id', md.checkAccountId, async (req, res, next) => {
// DO YOUR MAGIC
try {
await Account.deleteById(req.params.id)
res.json(req.accout)
} catch(err) {
next(err)
}
})

// General Error Handling Middleware
router.use((err, req, res, next) => { // eslint-disable-line
// DO YOUR MAGIC
res.status(err.status || 500).json({
message: err.message,
})

})

module.exports = router;
13 changes: 13 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
const express = require("express");

// Bring in Accounts Router
const accountsRouter = require('./accounts/accounts-router');

const server = express();

server.use(express.json());

// Connect the router exactly here, after json but before endpoint
server.use('/api/accounts', accountsRouter);

// Global Endpoint
server.use('*', (req, res) => {
res.status(404).json({
message: 'not found',
})
})

module.exports = server;
1 change: 1 addition & 0 deletions budget:=2000
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"message":"err is not defined"}
Binary file modified data/budget.db3
Binary file not shown.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const server = require("./api/server.js");

const PORT = process.env.PORT || 9000;
const PORT = process.env.PORT || 5001;

server.listen(PORT, () => {
console.log(`\n== API running on port ${PORT} ==\n`);
Expand Down
1 change: 1 addition & 0 deletions name=account-13
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"message":"err is not defined"}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"test": "cross-env NODE_ENV=testing jest --verbose --runInBand",
"test": "cross-env NODE_ENV=testing jest --verbose --runInBand --watch",
"resetdb": "knex migrate:rollback && knex migrate:latest && knex seed:run"
},
"dependencies": {
Expand Down