Step 2

The index.js file for the YouNote API contains several routing methods related to CRUD operations for notes. It is perceivable that we will have other resources/entities, such as users, in this application. It will likely be the case that we will need several other routing methods for CRUD operations for other resources.

Express has a Router object that enables you to move routing logic into a separate file. We will use the express router to refactor routing code.

Create a folder routes inside the younote-api folder. The files in this folder will contain all of our routes and we will export them using the express router.

Create a file notes.js inside routes folder. Copy and paste the content of index.js into notes.js. We will now make the following updates:

  1. Remove the following statements

    - const port = 4567;
    
    - app.use(express.json());
    
    - app.listen(port, () => {
    -    console.log(`Server is listening on http://localhost:${port}`);
    - });
    
  2. Update the path to NoteDao

    - const NoteDao = require("./model/NoteDao.js");
    + const NoteDao = require("../model/NoteDao.js");
    
  3. Make the following update

    - const app = express();
    + const app = express.Router();
    

    The Router() returns an an object with similar HTTP methods (.get, .post, .put, .delete, etc) to the app object we have previously been using.

  4. Rename app variable to router (you must apply this consistently to all instances of app in note.js file). This renaming is not a "must"; it is a good name choice though.

  5. Add the following statement to the end of note.js file

    module.exports = router;
    
  6. Update index.js to simply contain the following:

    const express = require("express");
    const noteRoutes = require("./routes/notes.js");
    const app = express();
    const port = process.env.PORT || 4567;
    
    app.use(express.json());
    app.use(noteRoutes);
    
    app.listen(port, () => {
      console.log(`Server is listening on http://localhost:${port}`);
    });
    

    The routes related to "notes" are now encapsulated within noteRoutes object and the express app is told to "use" it. Notice that I've also updated the declaration of port with somewhat forward thinking for when we deploy this application on Heroku.

Run the API server and run the API requests in Postman to ensure this refactoring has not broken our API's behavior.