Finished restful code

This commit is contained in:
fkereki
2018-05-21 22:39:08 -04:00
parent d149252226
commit 4cc40a73ad
2 changed files with 74 additions and 74 deletions
+46 -21
View File
@@ -1,8 +1,6 @@
/* @flow */
"use strict";
/* eslint-disable */
const getRegion = async (
res: any,
dbConn: any,
@@ -13,15 +11,26 @@ const getRegion = async (
let sqlQuery = "";
if (country == null) {
sqlQuery = `
SELECT rr.*, cc.countryName
SELECT rr.*
FROM regions rr
JOIN countries cc
ON cc.countryCode=rr.countryCode
ORDER BY cc.countryCode, rr.regionCode
`;
} else if (id == null) {
} else if (region == null) {
sqlQuery = `
SELECT rr.*, cc.countryName
SELECT 1
FROM countries
WHERE countryCode="${country}"
`;
const countries = await dbConn.query(sqlQuery);
if (countries.length === 0) {
return res.status(404).send("Country not found");
}
sqlQuery = `
SELECT rr.*
FROM regions rr
JOIN countries cc
ON cc.countryCode=rr.countryCode
@@ -30,7 +39,7 @@ const getRegion = async (
`;
} else {
sqlQuery = `
SELECT rr.*, cc.countryName
SELECT rr.*
FROM regions rr
JOIN countries cc
ON cc.countryCode=rr.countryCode
@@ -40,12 +49,16 @@ const getRegion = async (
}
const regions = await dbConn.query(sqlQuery);
res
.status(200)
.set("Content-Type", "application/json")
.send(JSON.stringify(regions));
if (regions.length > 0 || region === null) {
res
.status(200)
.set("Content-Type", "application/json")
.send(JSON.stringify(regions));
} else {
res.status(404).send("Not found");
}
} catch (e) {
res.status(500).send("Server error");
res.status(500).send("Server error 1");
}
};
@@ -60,11 +73,11 @@ const deleteRegion = async (
SELECT 1 FROM cities
WHERE countryCode="${country}"
AND regionCode="${region}"
LIMIT 1"
LIMIT 1
`;
const cities = await dbConn.query(sqlCities);
if (cities.length > 0) {
res.status(403).send("Cannot delete a region with cities");
res.status(405).send("Cannot delete a region with cities");
} else {
const deleteRegion = `
DELETE FROM regions
@@ -73,8 +86,7 @@ const deleteRegion = async (
`;
const result = await dbConn.query(deleteRegion);
if (result.affectedRows > 0) {
if (result.info.affectedRows > 0) {
res.status(204).send("Region deleted");
} else {
res.status(404).send("Region not found");
@@ -91,6 +103,10 @@ const postRegion = async (
country: string,
name: string
) => {
if (!name) {
return res.status(400).send("Missing name");
}
try {
const sqlCountry = `
SELECT 1
@@ -103,12 +119,13 @@ const postRegion = async (
}
const sqlGetId = `
SELECT MAX(regionCode) AS maxr
SELECT MAX(CAST(regionCode AS INTEGER)) AS maxr
FROM regions
WHERE countryCode="${country}"
`;
const regions = await dbConn.query(sqlCountry);
const newId = regions.length === 0 ? 1 : 1 + regions[0].maxr;
const regions = await dbConn.query(sqlGetId);
const newId =
regions.length === 0 ? 1 : 1 + Number(regions[0].maxr);
const sqlAddRegion = `
INSERT INTO regions SET
@@ -118,8 +135,11 @@ const postRegion = async (
`;
const result = await dbConn.query(sqlAddRegion);
if (result.affectedRows > 0) {
res.status(201).send("Region created");
if (result.info.affectedRows > 0) {
res
.status(201)
.header("Location", `/regions/${country}/${newId}`)
.send("Region created");
} else {
res.status(409).send("Region not created");
}
@@ -135,6 +155,10 @@ const putRegion = async (
region: string,
name: string
) => {
if (!name) {
return res.status(400).send("Missing name");
}
try {
const sqlUpdateRegion = `
UPDATE regions
@@ -144,7 +168,8 @@ const putRegion = async (
`;
const result = await dbConn.query(sqlUpdateRegion);
if (result.affectedRows > 0) {
if (result.info.affectedRows > 0) {
res.status(204).send("Region updated");
} else {
res.status(409).send("Region not updated");
+28 -53
View File
@@ -3,13 +3,25 @@
const express = require("express");
const app = express();
const jwt = require("jsonwebtoken");
const bodyParser = require("body-parser");
const validateUser = require("./validate_user.js");
const dbConn = require("./restful_db.js");
app.get("/", (req, res) => res.send("Secure server!"));
/*
Add here the logic for CORS
*/
const cors = require("cors");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
/*
Add here the logic for providing a JWT at /gettoken
and the logic for validating a JWT, as shown earlier
*/
const {
getRegion,
deleteRegion,
@@ -17,51 +29,6 @@ const {
putRegion
} = require("./restful_regions.js");
const SECRET_JWT_KEY = "modernJSbook";
app.use(bodyParser.urlencoded({ extended: false }));
app.post("/gettoken", (req, res) => {
validateUser(req.body.user, req.body.password, (idErr, userid) => {
if (idErr !== null) {
res.status(401).send(idErr);
} else {
jwt.sign(
{ userid },
SECRET_JWT_KEY,
{ algorithm: "HS256", expiresIn: "1h" },
(err, token) => res.status(200).send(token)
);
}
});
});
/*
app.use((req, res, next) => {
// First check for the Authorization header
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).send("No token specified");
}
// Now validate the token itself
const token = authHeader.split(" ")[1];
jwt.verify(token, SECRET_JWT_KEY, (err, decoded) => {
if (err) {
// Token bad formed, or expired, or other problem
return res.status(403).send("Token expired or not valid");
} else {
// Token OK; get the user id from it
req.userid = decoded.userid;
// Keep processing the request
next();
}
});
});
*/
// START ROUTING FOR REGIONS
app.get("/regions/", (req, res) => getRegion(res, dbConn));
app.get("/regions/:country/", (req, res) =>
@@ -90,14 +57,22 @@ app.put("/regions/:country/:region", (req, res) =>
)
);
// END OF ROUTING FOR REGIONS
// 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("Mini JWT server ready, at http://localhost:8080/!")
);
/*
Add here the logic for HTTPS
*/
const https = require("https");
const fs = require("fs");
const path = require("path");
const keysPath = path.join(__dirname, "../../certificates");
const ca = fs.readFileSync(`${keysPath}/modernjsbook.csr`);
const cert = fs.readFileSync(`${keysPath}/modernjsbook.crt`);
const key = fs.readFileSync(`${keysPath}/modernjsbook.key`);
https.createServer({ ca, cert, key }, app).listen(8443);