app.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import 'dotenv/config'
  2. import express from "express"
  3. import bodyParser from "body-parser"
  4. import basicAuth from "express-basic-auth"
  5. const app = express();
  6. app.use(bodyParser.json());
  7. app.use(basicAuth({
  8. users : { 'admin' : 'superPasswd' },
  9. challange : true
  10. }));
  11. const CHAIN4ALL_SERVICE_PORT = process.env.CHAIN4ALL_SERVICE_PORT || 3000;
  12. const IROHA_API_HOST = process.env.IROHA_API_HOST || "http://localhost";
  13. const IROHA_API_PORT = process.env.IROHA_API_PORT || 5000;
  14. const IROHA_DOMAIN = process.env.IROHA_DOMAIN || "test";
  15. const IROHA_ASSET = process.env.IROHA_ASSET || "coin";
  16. const DATA_OWNER = process.env.DATA_OWNER || "admin"
  17. const PRICE_MODIFIER = process.env.PRICE_MODIFIER || 0.5;
  18. app.get("/", (req, res) => {
  19. res.send("Chain4All Blockchain service");
  20. });
  21. app.post("/price", (req, res) => {
  22. if (req.body && req.body.extent) {
  23. res.send({ price: getPrice(req.body.extent) });
  24. }
  25. else {
  26. res.status(400);
  27. throw Error(JSON.stringify({ error: { name: "Error, request has no body with \"extent\" property!" } }));
  28. }
  29. });
  30. app.post("/buy", async (req, res, next) => {
  31. try {
  32. if (!req.body) {
  33. res.status(400);
  34. throw Error(JSON.stringify({ error: { name: "Error, request has no body!" } }));
  35. }
  36. if (!req.body.txHash) {
  37. res.status(400);
  38. throw Error(JSON.stringify({ error: { name: "Error, request body has no \"txHash\" property!" } }));
  39. }
  40. }
  41. catch (err) {
  42. next(err);
  43. }
  44. });
  45. function getArea(extent) {
  46. let y1 = extent[0][1];
  47. let y4 = extent[3][1];
  48. let x1 = extent[0][0];
  49. let x2 = extent[1][0];
  50. let height = Math.abs(y1 - y4);
  51. let width = Math.abs(x1 - x2);
  52. return height * width;
  53. }
  54. function getPrice(extent) {
  55. return getArea(extent) * PRICE_MODIFIER;
  56. }
  57. function errorMiddleware(err, req, res, next) { //TODO: add custom Exception class
  58. console.log(err);
  59. res.status(500);
  60. res.send(err.message);
  61. }
  62. app.use(errorMiddleware);
  63. app.listen(CHAIN4ALL_SERVICE_PORT, () => {
  64. console.log(`Listening at http://localhost:${CHAIN4ALL_SERVICE_PORT}`)
  65. });