Преглед изворни кода

leaflet: outsource db helper

Bernadette Elena Hammerle пре 4 година
родитељ
комит
44248c0236
2 измењених фајлова са 91 додато и 59 уклоњено
  1. 31 59
      src/Leaflet.js
  2. 60 0
      src/helpers/dbHelpers.js

+ 31 - 59
src/Leaflet.js

@@ -10,78 +10,50 @@ import {
 import "./css/maps.css";
 import {calcDistance} from "./helpers/distance";
 import {longitude, latitude, mapWidth, mapHeight, testPath} from "./config/variables";
-import {Button, Input} from 'reactstrap';
+import {Button, Input} from "reactstrap";
+import {fetchPathKeys, fetchPaths, savePathToDb} from "./helpers/dbHelpers.js"
 
 export default class Leaflet extends React.Component{
-  state = {
-    latitude: latitude,
-    longitude: longitude,
-    zoom: 15,
-    path: testPath,
-    distance: 0,
-    pathKey: "",
-    pathKeys: [],
-    savePathKey: "-"
+  constructor(props){
+    super(props);
+    this.state = {
+      latitude: latitude,
+      longitude: longitude,
+      zoom: 15,
+      path: testPath,
+      distance: 0,
+      pathKey: "",
+      pathKeys: [],
+      savePathKey: "-"
     }
 
+    this.savePathToDb = savePathToDb.bind(this)
+  }
+
   componentDidMount(){
-    this.fetchPathKeys()
+    this.getPathKeys()
   }
 
-  fetchPath = () => {
-    fetch("http://localhost:5000/get-path")
-      .then(res => {
-        if(res.status >= 400) {
-            throw new Error("Server responds with error!");
-        }
-        return res.json();
-      }).then(data => {
-        this.setState({path: data[this.state.pathKey]})
-        this.getDistance()
-      }, err => {
-        console.log(err)
-      })
+  getPathKeys = () => {
+    fetchPathKeys().then(keys => this.setState({pathKeys: keys}))
   }
 
-  fetchPathKeys = () => {
-    fetch("http://localhost:5000/get-path")
-      .then(res => {
-        if(res.status >= 400) {
-            throw new Error("Server responds with error!");
-        }
-        return res.json();
-      }).then(data => {
-        this.setState({pathKeys: Object.keys(data)})
-      }, err => {
-        console.log(err)
-      });
+  getPath = () => {
+    fetchPaths().then(paths => this.setState({path: paths[this.state.pathKey]}))
+    this.getDistance()
   }
 
-  getPath = (event) => {
+  choosePath = (event) => {
     this.setState({pathKey: event.target.value})
-    this.fetchPath()
+    this.getPath()
   }
 
   savePath = () => {
-    let json = JSON.stringify({
-        "path": {
-          "name": this.state.savePathKey,
-          "coords": this.state.path
-        }
-      })
-    fetch("http://localhost:5000/set-path", {
-      method: 'POST',
-      headers: {
-        'Accept': 'application/json',
-        'Content-Type': 'application/json',
-      },
-      body: json
-    }).then(res => res.json)
-      .then(data => {
-        let pathKeyCopy = this.state.pathKeys.slice();
-        pathKeyCopy.push(this.state.savePathKey);
-        this.setState({pathKeys: pathKeyCopy, savePathKey: ""})
-      })
+    this.savePathToDb().then(res => {
+      let pathKeysCopy = this.state.pathKeys.slice();
+      pathKeysCopy.push(this.state.savePathKey);
+      this.setState({pathKeys: pathKeysCopy, savePathKey: ""})
+    })
   }
 
   setSavePathKey = (event) => {
@@ -112,7 +84,7 @@ export default class Leaflet extends React.Component{
   clearPath = () => {
     this.setState({path: [], distance: 0})
   }
-  
+
   render() {
     const position = [this.state.latitude, this.state.longitude]
     return (
@@ -155,7 +127,7 @@ export default class Leaflet extends React.Component{
           <Input type="text" onChange={this.setSavePathKey} value={this.state.savePathKey}/>
           <Button onClick={this.savePath}>save path</Button>
 
-          <Input type="select" name="select" id="savePath" onChange={this.getPath.bind(this)}>
+          <Input type="select" name="select" id="savePath" onChange={this.choosePath.bind(this)}>
             {this.state.pathKeys.map((name, idx) =>
               <option value={name} key={idx}>{name}</option>
             )}

+ 60 - 0
src/helpers/dbHelpers.js

@@ -0,0 +1,60 @@
+export const fetchPathKeys = () => {
+  return fetch("http://localhost:5000/get-path")
+    .then(res => {
+      if(res.status >= 400) {
+        throw new Error("Server responds with error!");
+      }
+      return res.json();
+    }).then(data => {
+      return Object.keys(data)
+    }, err => {
+      console.log(err)
+    });
+}
+
+
+export const fetchPaths = () => {
+  return fetch("http://localhost:5000/get-path")
+    .then(res => {
+      if(res.status >= 400) {
+          throw new Error("Server responds with error!");
+      }
+      return res.json();
+    }).then(data => {
+      return data
+    }, err => {
+      console.log(err)
+    })
+}
+
+
+export function savePathToDb(){
+  let json = JSON.stringify({
+      "path": {
+        "name": this.state.savePathKey,
+        "coords": this.state.path
+      }
+    })
+  
+  let reqOptions = {
+    method: 'POST',
+    headers: {
+      'Accept': 'application/json',
+      'Content-Type': 'application/json',
+    },
+    body: json
+  }
+  
+  return fetch("http://localhost:5000/set-path", reqOptions)
+    .then(res => {
+      if(res.status >= 400) {
+          throw new Error("Server responds with error!");
+      }
+      return res.json();
+    })
+    .then(data => {
+      return data
+    }, err => {
+      console.log(err)
+    })
+}