Refactoring routes

We previously created the teams-api.js file in the routes folder. Open that file and apply the following changes:

const express = require('express')
const api = new express.Router()

let teams = [
{ id: 1, name: "Peru"},
{ id: 2, name: "Russia"}
]

First, we import the express module. From this module, we are declaring the api variable, which is an instance of express.Router. A teams variable has been created in order to host some fake data for the teams. We will use this router to configure our CRUD/HTTP handlers, as follows:

api
.route('/teams')
.get((req, res) => {
res.json(teams)
})
.post((req, res) => {

})

app.listen(3000, () => {
...

Using the api route variable, we define the '/teams' path as root for the HTTP handlers. In the get handler, we are just sending the list of teams as the response.

Lastly, we need to export the api route to be used in the server.js file:

...
module.exports = api

Once we are ready, open the server.js file to apply the following changes that will configure the server to use this route:

const express = require('express')
const bodyParser = require('body-parser')
const teamsApi = require('./src/routes/teams-api')
const app = express()

app.use(bodyParser.json())
app.use(teamsApi)

...

First, we import the Teams API module from the relative path into our project and use the app.use function to configure our routes. Let's test things out; run the following command in your Terminal:

$ curl -X GET localhost:3000/teams

[{"id": 1, "name":"Peru"},{"id": 2, "name":"Russia"}]

Cool! Now we have our code clean and everything is working as we expect. It's time to write some code to implement the POST, PUT, and DELETE handlers. We will use the fake teams variable to add data in memory until we learn how to use a real database in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.123