Skip to content

Instantly share code, notes, and snippets.

@dustinmyers
Last active May 24, 2018 16:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinmyers/07f2d91feb5e513833829fae263d6977 to your computer and use it in GitHub Desktop.
Save dustinmyers/07f2d91feb5e513833829fae263d6977 to your computer and use it in GitHub Desktop.
Node II

Review

Work through node-express-mini

  • CRUD
    • Create
    • Read
    • Update
    • Delete
  • REST
    • GET
    • PUT
    • POST
    • DELETE
  • Middleware - use built-in and third party Middleware
  • Modularize routes using express.Router()

Topics

  • Configuring sub-routes
  • Ordering routes
  • Configuring CORS for SPA + API architecture

Review Questions - review and build

What is CRUD? What is REST? How are they similar / different? What problem are they trying to solve?

What is middleware? What is middleware used for?

  • Third-party middleware
  • Custom middleware

How do you use middleware?

What does modularize mean? How do we "modularize" code? What benefits does modularizing have?

Some new stuff!!

Configuring sub routes

Hair salon app

With schemas for Customers, Appointments, and Products in your database, what are some different ways you could display that data in a React app?

Project calls for:

  • List of customers
  • List of appointments for a customer
  • List of customers that have purchased a specific product
  • List of customers with no scheduled appointment

Subroutes to the rescue!

GET '/api/customers'; GET '/api/customers/no-appointments' GET 'api/products/:id/customers

||

GET 'api/products/:id?hasPurchased=true

REST constraints:

  • Stateless - requests don't rely on each other
  • uniform interfaces

Ordering subroutes

Time to fail!!

CORS for a SPA

What is it? What problem is it solving? How do we use it?

Any Questions???

module.exports = {
logger,
greeter,
};
// logger middleware --> function that we call somewhere else
function logger(msg) {
return function(req, res, next) {
console.log(`${msg || 'requesting'}: ${req.url}`);
next();
}
}
function greeter() {
return function(req, res, next) {
if (req.query.passcode === 'gandalf') { // query string is after the "?" -> /books/lotr?title=Hobbit&character=Bilbo
next();
} else {
res.send('YOU SHALL NOT PASS!!!')
}
}
}
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const { logger, greeter } = require('./middleware');
const userRoutes = require('./users/userRoutes');
const server = express();
// add middleware
server.use(express.json());
server.use(cors());
server.use(helmet()); // 3
server.use(logger('loading'));
server.use(greeter());
// user route handlers
server.use('/api/users', userRoutes); // /api/users || api/users/:id || api/users/something-else
const port = 8000;
server.listen(port, () => console.log(`\n== API Running on port ${port} ==\n`));
const express = require('express');
const db = require('../data/db');
const { logger } = require('../middleware');
const router = express.Router(); // black magic
// protected routes ==> routes that require authentication
router.get('/', logger('loading from user module'), (req, res) => { // <-- REST Action/operation (client -> server)
db.find() // <-- CRUD action/operation (server querying database)
.then(response => { // <-- finishes CRUD operation (database -> server)
res.status(200);
res.json(response); // <-- finish REST operation (server -> client)
})
});
router.get('/say-hello', (req, res) => {
res.send('hello');
});
router.get('/:id', (req, res) => {
db.findById(req.params.id)
.then(response => {
console.log(response);
res.json(response[0]);
})
});
// Out of order! This would never be reached!!!
// router.get('/say-hello', (req, res) => {
// res.send('hello');
// });
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment