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
Binary file added api/.DS_Store
Binary file not shown.
53 changes: 53 additions & 0 deletions api/hubs/hubs-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const db = require('../../data/dbConfig.js');

module.exports = {
find,
findById,
add,
remove,
update,
findHubMessages
};

function find(query) {
let { page = 1, limit = 5, sortby = 'id', sortdir = 'asc' } = query;
const offset = limit * (page - 1);

let rows = db('hubs')
.orderBy(sortby, sortdir)
.limit(limit)
.offset(offset);

return rows;
}

function findById(id) {
return db('hubs')
.where({ id })
.first();
}

async function add(hub) {
const [id] = await db('hubs').insert(hub);

return findById(id);
}

function remove(id) {
return db('hubs')
.where({ id })
.del();
}

function update(id, changes) {
return db('hubs')
.where({ id })
.update(changes, '*');
}

function findHubMessages(hubId) {
return db('messages as m')
.join('hubs as h', 'm.hub_id', 'h.id')
.select('m.id', 'm.text', 'm.sender', 'h.id as hubId', 'h.name as hub')
.where({ hub_id: hubId });
}
117 changes: 117 additions & 0 deletions api/hubs/hubs-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
const express = require('express');

const Hubs = require('./hubs-model.js');
const Messages = require('../messages/messages-model.js');

const router = express.Router();

// middleware
const checkHubId = async (req, res, next) => {
const {id} = req.params;

try {
const hub = await Hubs.findById(id);

if (!hub) {
res.status(404).json({message: `no hub ${id}, error`})
} else {
req.hub = hub; // take the request object and make a new property inside it
next();
}

} catch(e) {
res.status(500).json({message: e.message})
}
}

const checkMessage = (req, res, next) => { // middleware to check the payload
if (!req.body.sender || !req.body.text) {
res.status(400).json("message and sender required")
} else {
next();
}
}

router.get('/', (req, res, next) => {
Hubs.find(req.query)
.then(hubs => {
res.status(200).json(hubs);
})
.catch(error => {
// log error to server
next(error)
});
});

router.get('/:id', checkHubId, (req, res, next) => {
res.status(200).json(req.hub); // this is from the new property we just made in the middleware
});

router.post('/', (req, res) => {
Hubs.add(req.body)
.then(hub => {
res.status(201).json(hub);
})
.catch(error => {
// log error to server
next(error)
});
});

router.delete('/:id', checkHubId, (req, res, next) => {
Hubs.remove(req.params.id)
.then(() => {
res.status(200).json({ message: 'The hub has been nuked' });
})
.catch(error => {
// log error to server when we try to delete the hub, after we already checked the id
next(error)
});
});

router.put('/:id', checkHubId, (req, res, next) => {
Hubs.update(req.params.id, req.body)
.then(hub => {
res.status(200).json(hub);
})
.catch(error => {
// log error to server
next(error)
});
});

router.get('/:id/messages', checkHubId, (req, res, next) => {
Hubs.findHubMessages(req.params.id)
.then(messages => {
res.status(200).json(messages);
})
.catch(error => {
// log error to server
next(error)
});
});

router.post('/:id/messages', checkHubId, checkMessage, (req, res, next) => {
const messageInfo = { ...req.body, hub_id: req.params.id };

Messages.add(messageInfo)
.then(message => {
res.status(210).json(message);
})
.catch(error => {
// log error to server
next(error)
});
});

// ERROR ENDPOINT
// ERROR ENDPOINT
// ERROR ENDPOINT
router.use((err, req, res, next) => {
res.status(500).json({
message: 'Error somewhere in there my dude',
error: err.message
});
})

module.exports = router;
45 changes: 45 additions & 0 deletions api/messages/messages-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const db = require('../../data/dbConfig.js');

module.exports = {
find,
findById,
add,
remove,
update
};

function find(query) {
let { page = 1, limit = 5, sortby = 'id', sortdir = 'asc' } = query;
const offset = limit * (page - 1);

let rows = db('messages')
.orderBy(sortby, sortdir)
.limit(limit)
.offset(offset);

return rows;
}

function findById(id) {
return db('messages')
.where({ id })
.first();
}

async function add(message) {
const [id] = await db('messages').insert(message);

return findById(id);
}

function remove(id) {
return db('messages')
.where({ id })
.del();
}

function update(id, changes) {
return db('messages')
.where({ id })
.update(changes, '*');
}
30 changes: 30 additions & 0 deletions api/middlewares/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// make your own middleware [ client --> Middleware (call next()) --> server ] / pay close attention to where and when your middleweare is being applied
const logQuote = (coin) => (req, res, next) => {
console.log('a penny saved is a penny earned');

if (coin == 'quarter') {
console.log('yeet');
next();
} else if (coin == 'penny' || 'nickle') {
console.log(`smol ${coin} bb`);
next();
} else {
res.json("not a valid coin");
}

}

const checkWord = (req, res, next) => {
if (req.query.word === "bad") {
res.json(`you can't proceed with the word: ${req.query.word}`);
} else {
next();
}
}



module.exports = {
logQuote,
checkWord
}
31 changes: 31 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const express = require('express'); // importing a CommonJS module

const hubsRouter = require('./hubs/hubs-router.js');

const morgan = require("morgan")
const helmet = require("helmet")

const { logQuote, checkWord } = require('./middlewares/middleware')

const server = express();

server.use(express.json());
server.use(morgan("dev")) // global middleware, in the console, lets you know what end point, the status, and how long it took to do
server.use(helmet()) // global middlewear that protects header in requests
server.use(logQuote("penny")) // your own middleware

server.use('/api/hubs', hubsRouter);

server.get('/', checkWord, (req, res) => {
res.send(`
<h2>Hubs API</h2>
<p>Welcome to the Hubs API</p>
`);
});

server.use('*', (req, res) => {
// catch all 404 errors middleware
res.status(404).json({ message: `${req.method} ${req.baseUrl} not found!` });
});

module.exports = server;
Binary file added data/.DS_Store
Binary file not shown.
5 changes: 5 additions & 0 deletions data/dbConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const knex = require('knex');

const config = require('../knexfile.js');

module.exports = knex(config.development);
Binary file added data/hubs.db3
Binary file not shown.
25 changes: 25 additions & 0 deletions data/migrations/20190211125952_bootstrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
exports.up = function (knex) {
return knex.schema
.createTable('hubs', tbl => {
tbl.increments();
tbl.string('name').notNullable().unique();
})
.createTable('messages', tbl => {
tbl.increments();
tbl.string('sender').notNullable();
tbl.text('text').notNullable();
tbl.integer('hub_id')
.unsigned()
.notNullable()
.references('id')
.inTable('hubs')
.onDelete('CASCADE')
.onUpdate('CASCADE');
});
};

exports.down = function (knex) {
return knex.schema
.dropTableIfExists('messages')
.dropTableIfExists('hubs');
};
8 changes: 8 additions & 0 deletions data/seeds/000-cleanup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const cleaner = require('knex-cleaner');

exports.seed = function(knex) {
return cleaner.clean(knex, {
mode: 'truncate',
ignoreTables: ['knex_migrations', 'knex_migrations_lock'],
});
};
24 changes: 24 additions & 0 deletions data/seeds/001-hubs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
exports.seed = function(knex, Promise) {
return knex('hubs').insert([
{ name: 'api-1' }, // 1
{ name: 'api-2' }, // 2
{ name: 'api-3' }, // 3
{ name: 'api-4' }, // 4
{ name: 'db-1' }, // 5
{ name: 'db-2' }, // 6
{ name: 'db-3' }, // 7
{ name: 'db-4' }, // 8
{ name: 'auth-1' }, // 9
{ name: 'auth-2' }, // 10
{ name: 'auth-3' }, // 11
{ name: 'auth-4' }, // 12
{ name: 'testing-1' }, // 13
{ name: 'testing-2' }, // 14
{ name: 'testing-3' }, // 15
{ name: 'testing-4' }, // 16
{ name: 'build-1' }, // 17
{ name: 'build-2' }, // 18
{ name: 'build-3' }, // 19
{ name: 'build-4' }, // 20
]);
};
Loading