| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- import fetch from "node-fetch"
- import express from "express"
- import bodyParser from "body-parser"
- const app = express();
- app.use(bodyParser.json());
- const CHAIN4ALL_SERVICE_PORT = process.env.CHAIN4ALL_SERVICE_PORT || 3000;
- const IROHA_API_HOST = process.env.IROHA_API_HOST || "http://localhost";
- const IROHA_API_PORT = process.env.IROHA_API_PORT || 5000;
- const IROHA_DOMAIN = process.env.IROHA_DOMAIN || "test";
- const PRICE_MODIFIER = 0.5;
- app.post("/price", (req, res) => {
- if(req.body && req.body.extent){
- req.body.price = getPrice(req.body.extent);
- res.send(req.body);
- }
- else{
- res.status(400);
- res.send();
- }
- });
- app.get("/users/:userId/assets", async (req, res) => {
- let irohaResponse = await fetchUsersAssets(req.params.userId);
- res.status(irohaResponse.status);
- if(irohaResponse.headers.get("content-length") < 1){
- res.send();
- }
- else{
- res.send(await irohaResponse.json());
- }
- });
- app.get("/users/:userId/assets/:assetId", async (req, res) => {
- let assets = (await fetchUsersAssets(req.params.userId)).assets;
-
- let parsedAssetName = "";
- let i = 0;
- for(i; i < assets.length; i++){
- parsedAssetName = assets[i].assetId.split('#')[0];
- if(parsedAssetName === req.params.assetId){
- res.status(200);
- res.send(assets[i]);
- return;
- }
- }
- res.status(204);
- res.send();
- });
- app.post("/buy", (req, res) => {
- //TODO implement...
- res.status(201);
- });
- async function fetchUsersAssets(userId){
- return await fetch(IROHA_API_HOST + ':' + IROHA_API_PORT + '/accounts/' + userId + '@' + IROHA_DOMAIN + '/assets/');
- }
- function getArea(extent){
- let y1 = extent[0][1];
- let y4 = extent[3][1];
- let x1 = extent[0][0];
- let x2 = extent[1][0];
- let height = Math.abs(y1 - y4);
- let width = Math.abs(x1 - x2);
- return height * width;
- }
- function getPrice(extent){
- return getArea(extent) * PRICE_MODIFIER;
- }
- function error(err, req, res, next){
- console.log(err);
- res.status(500);
- res.send("Something went wrong. Here is the error message: " + err.message);
- }
- app.use(error);
- app.listen(CHAIN4ALL_SERVICE_PORT, () => {
- console.log(`Listening at http://localhost:${CHAIN4ALL_SERVICE_PORT}`)
- });
|