Thanks to Express, we won't need too much code, with only two new lines to enable our routing; check out the following code:
// Source file: src/routing.js
/* @flow */
"use strict";
const express = require("express");
const app = express();
const myRouter = require("./router_home.js");
app.use("/", myRouter);
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
console.error("Error....", err.message);
res.status(500).send("INTERNAL SERVER ERROR");
});
app.listen(8080, () =>
console.log("Routing ready at http://localhost:8080")
);
The router_home.js module could have the first level of route branching, as shown in the following code:
// Source file: src/router_home.js
/* @flow */
"use strict";
const express = require("express");
const routerHome = express.Router();
const routerCountries = require("./router_countries.js");
const routerRegions = require("./router_regions.js");
const routerCities = require("./router_cities.js");
routerHome.use("/countries", routerCountries);
routerHome.use("/regions", routerRegions);
routerHome.use("/cities", routerCities);
module.exports = routerHome;
And, going down one more level, we'd have three more files specifying the next levels. For example, routing for countries would be as follows. You'll note a weird extra route, /URUGUAY, which I added just to show you that we can have more routes than a RESTful server would require!
// Source file: src/router_countries.js
/* @flow */
"use strict";
const express = require("express");
const routerCountries = express.Router();
routerCountries.get("/", (req, res) => {
res.send(`All countries... path=${req.originalUrl}`);
});
routerCountries.get("/URUGUAY", (req, res) => {
res.send(`GET UY (Uruguay)... path=${req.originalUrl}`);
});
routerCountries.get("/:country", (req, res) => {
res.send(`GET Single country... ${req.params.country}`);
});
module.exports = routerCountries;
The regions routing file will be as shown in the following code, and we'll skip the cities routing since it's quite similar to countries routing:
// Source file: src/router_regions.src
/* @flow */
"use strict";
const express = require("express");
const routerRegions = express.Router();
routerRegions.get("/", (req, res) => {
res.send(`Region GET ALL... `);
});
routerRegions.get("/:country", (req, res) => {
res.send(`Region GET ALL FOR Country=${req.params.country}`);
});
routerRegions.get("/:country/:id", (req, res) => {
res.send(`Region GET ${req.params.country}/${req.params.id}`);
});
routerRegions.delete("/:country/:id", (req, res) => {
res.send(`Region DELETE... ${req.params.country}/${req.params.id}`);
});
routerRegions.post("/", (req, res) => {
res.send(`Region POST... `);
});
routerRegions.put("/:country/:id", (req, res) => {
res.send(`Region PUT... ${req.params.country}/${req.params.id}`);
});
module.exports = routerRegions;
You can read more about Express routing at https://expressjs.com/en/starter/basic-routing.html and https://expressjs.com/en/guide/routing.html.