Skip to content

Instantly share code, notes, and snippets.

@cklanac
Last active October 12, 2019 01:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cklanac/96c383d6d9a83ce002a288147f3b4ce7 to your computer and use it in GitHub Desktop.
Save cklanac/96c383d6d9a83ce002a288147f3b4ce7 to your computer and use it in GitHub Desktop.
Challenge 03: RESTful and Express Routers

For this challenge, you'll add the save and delete features. And, you'll move the endpoints into a router.

Requirements

  • Swap out the custom logger with Morgan
  • Move endpoints to an Express Router
  • Implement save a new Note feature
  • Implement delete a Note feature

Before getting started, remember to create a development branch git checkout -b feature/restful-routers to hold your work.

Swap out your custom logger with Morgan

Let's replace your custom logger with Morgan, a popular HTTP request logger middleware for Node.

You have installed NPM packages before so we'll skip with step-by-step instructions and simply provide a friendly reminder, then you can do your thing.

Remember that in NPM v5.x and up, saving the package to the dependencies property is now the default, so the --save flag is optional. But it is good practice to double-check the dependencies property in the package.json file to ensure the package was added correctly.

You're up!

  • NPM install Morgan and configure it to use the dev predefined format.
  • Verify Morgan is logging requests properly by hitting various endpoints using Postman and check the terminal for output.
    • Call a static file. Does it log the request?
    • Call the GET /api/notes and `/api/notes/:id/ endpoints. Does it log the requests as expected?
    • Call the GET or PUT /does/not/exist. Does it log the 404 response?

Note: Morgan does not write the log to the console immediately. Instead, it buffers the log until the reponse has been sent so that it can log the response code, content length, etc. You may notice that the log files are written after other console.log(...) statements in your application.

Commit your changes!

Move endpoints to Express Router

The server.js file is beginning to look a bit cluttered. Let's fix that by using Express Router to create maintanable, modular, mountable route handlers.

Your challenge is create and mount an Express router for /api/notes and verify it works properly. You worked on Modularizing with Express Router in the curriculum so we won't repeat the details here, but we have provided a list of the changes below. You can refer back to the assignment in the curriculum and Express Router documentation if needed.

  • Create /router/notes.router.js folder and file.
  • In /router/notes.router.js:
    • Require Express
    • Create a Router
    • Move the simDb related code from server.js the router file
    • Move the endpoints from server.js to the router file
    • Change app.METHOD to router.METHOD
    • Export the router
  • In /server.js:
    • Mount the router with app.use(...)

Before proceeding you should verify the changes by hitting each endpoint using Postman and check the results.

  • Does it return the correct data?
  • Does the Morgan still log correctly?

Mount the notes router on /api and remove /api from the endpoint paths:

  • In server.js, mount the router on /api:
    • change app.use(notesRouter) to app.use('/api', notesRouter)
  • And in notes.router.js remove /api from endpoints:
    • change router.get('/api/notes',... to router.get('/notes',...
    • change router.get('/api/notes/:id',... to router.get('/notes/:id',...

Confirm the changes are working properly by hitting each endpoint again using Postman.

Commit your changes!

Create new POST and DELETE endpoints

Congrats! Now let's implement the post and delete endpoints. We'll walk you thru the creating the new Note feature so you'll be able to implement the delete Note feature on your own.

Update the Server

In the notes router, create a POST /notes endpoint. Notice the similarities and differences between the POST and PUT endpoints.

// Post (insert) an item
router.post('/notes', (req, res, next) => {
  const { title, content } = req.body;

  const newItem = { title, content };
  /***** Never trust users - validate input *****/
  if (!newItem.title) {
    const err = new Error('Missing `title` in request body');
    err.status = 400;
    return next(err);
  }

  notes.create(newItem, (err, item) => {
    if (err) {
      return next(err);
    }
    if (item) {
      res.location(`http://${req.headers.host}/notes/${item.id}`).status(201).json(item);
    } else {
      next();
    }
  });
});

Use Postman to create a new Note and confirm the endpoint is working. Then call the GET /notes endpoint. Does the new note show up in the list? When you call GET /notes/:id with the new ID, does it return?

Commit your changes!

Add Delete Note

Your Turn!

Your challenge is to implement the delete note feature and test it with Postman

Requirements:

  • Should match requests to DELETE /api/notes/:id
  • Should delete the note from simDb using notes.delete( id, err => {})
  • If note is deleted then respond with status 204 "No Content"
  • If error is detected, then respond with status 500 and the error

Commit your changes!

Update Client

Your last task is to simple update the client to take advantage of the new features. Instead of making piecemeal changes, you can copy the code for public/scripts/api.js and public/scripts/noteful.js from this gist.

Feature / Noteful App V1 POST and DELETE Client update

Solutions

You can view an example solution and compare the differences between branches

Good Luck!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment