app.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import fetch from "node-fetch"
  2. import express from "express"
  3. import bodyParser from "body-parser"
  4. const app = express();
  5. app.use(bodyParser.json());
  6. const CHAIN4ALL_SERVICE_PORT = process.env.CHAIN4ALL_SERVICE_PORT || 3000;
  7. const IROHA_API_HOST = process.env.IROHA_API_HOST || "http://localhost";
  8. const IROHA_API_PORT = process.env.IROHA_API_PORT || 5000;
  9. const IROHA_DOMAIN = process.env.IROHA_DOMAIN || "test";
  10. const PRICE_MODIFIER = 0.5;
  11. app.post("/price", (req, res) => {
  12. if(req.body && req.body.extent){
  13. req.body.price = getPrice(req.body.extent);
  14. res.send(req.body);
  15. }
  16. else{
  17. res.status(400);
  18. res.send();
  19. }
  20. });
  21. app.get("/users/:userId/assets", async (req, res) => {
  22. let irohaResponse = await fetchUsersAssets(req.params.userId);
  23. res.status(irohaResponse.status);
  24. if(irohaResponse.headers.get("content-length") < 1){
  25. res.send();
  26. }
  27. else{
  28. res.send(await irohaResponse.json());
  29. }
  30. });
  31. app.get("/users/:userId/assets/:assetId", async (req, res) => {
  32. let assets = (await fetchUsersAssets(req.params.userId)).assets;
  33. let parsedAssetName = "";
  34. let i = 0;
  35. for(i; i < assets.length; i++){
  36. parsedAssetName = assets[i].assetId.split('#')[0];
  37. if(parsedAssetName === req.params.assetId){
  38. res.status(200);
  39. res.send(assets[i]);
  40. return;
  41. }
  42. }
  43. res.status(204);
  44. res.send();
  45. });
  46. app.post("/buy", (req, res) => {
  47. //TODO implement...
  48. res.status(201);
  49. });
  50. async function fetchUsersAssets(userId){
  51. return await fetch(IROHA_API_HOST + ':' + IROHA_API_PORT + '/accounts/' + userId + '@' + IROHA_DOMAIN + '/assets/');
  52. }
  53. function getArea(extent){
  54. let y1 = extent[0][1];
  55. let y4 = extent[3][1];
  56. let x1 = extent[0][0];
  57. let x2 = extent[1][0];
  58. let height = Math.abs(y1 - y4);
  59. let width = Math.abs(x1 - x2);
  60. return height * width;
  61. }
  62. function getPrice(extent){
  63. return getArea(extent) * PRICE_MODIFIER;
  64. }
  65. function error(err, req, res, next){
  66. console.log(err);
  67. res.status(500);
  68. res.send("Something went wrong. Here is the error message: " + err.message);
  69. }
  70. app.use(error);
  71. app.listen(CHAIN4ALL_SERVICE_PORT, () => {
  72. console.log(`Listening at http://localhost:${CHAIN4ALL_SERVICE_PORT}`)
  73. });