Skip to content
Open

mvp #589

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
39 changes: 37 additions & 2 deletions api/accounts/accounts-middleware.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,48 @@
const Account = require('./accounts-model')

exports.checkAccountPayload = (req, res, next) => {
// DO YOUR MAGIC
// Note: you can either write "manual" validation logic
// or use the Yup library (not currently installed)
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
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.param)
if(account) {
req.account = account
next()
}
} catch(err) {

}
}
19 changes: 16 additions & 3 deletions api/accounts/accounts-model.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
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 = id
return db('accounts').where('id', id).first()
}

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

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

const deleteById = id => {
// DO YOUR MAGIC
const deletedAccount = await getById(id)
await db('accounts').where('id', id).delete()
return deletedAccount
}

module.exports = {
Expand Down