Let's look at how we can write our server. We'll start with some basic code, skipping parts that we already saw earlier, such as CORS and JWT handling:
// Source file: src/restful_server.js
/* @flow */
"use strict";
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const dbConn = require("./restful_db.js");
app.get("/", (req, res) => res.send("Secure server!"));
/*
Add here the logic for CORS
*/
/*
Add here the logic for providing a JWT at /gettoken
and the logic for validating a JWT, as shown earlier
*/
Handling routing is quite standard. Since routes are simple and few, we may put them in the same source file; otherwise, we'd set up separate files for different sets of routes. The handlers for the routes will certainly go in another file ("restful_regions.js") so as not to obscure the main server code. Note that country and region codes are, if present, part of the URL; whenever the name for a region is needed, it goes in the body parameters:
// Source file: src/restful_server.js
const {
getRegion,
deleteRegion,
postRegion,
putRegion
} = require("./restful_regions.js");
app.get("/regions", (req, res) => getRegion(res, dbConn));
app.get("/regions/:country", (req, res) =>
getRegion(res, dbConn, req.params.country)
);
app.get("/regions/:country/:region", (req, res) =>
getRegion(res, dbConn, req.params.country, req.params.region)
);
app.delete("/regions/:country/:region", (req, res) =>
deleteRegion(res, dbConn, req.params.country, req.params.region)
);
app.post("/regions/:country", (req, res) =>
postRegion(res, dbConn, req.params.country, req.body.name)
);
app.put("/regions/:country/:region", (req, res) =>
putRegion(
res,
dbConn,
req.params.country,
req.params.region,
req.body.name
)
);
Finally, let's look at some more code that we've already seen to finish up the server, error handling and setting up the server itself:
// Source file: src/restful_server.js
// 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");
});
/*
Add here the logic for HTTPS, finishing with:
https.createServer({ ca, cert, key }, app);
*/
app.listen(8080, () =>
console.log("Routing ready at http://localhost:8080")
);
Let's move on and see how it works. We'll show the code for handling routes in the following section.