mahmoudabdelkhalk

DBHelper File

Aug 16th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Common database helper functions.
  3.  */
  4.  
  5. let dbpromise;
  6. class DBHelper {
  7.  
  8.   /**
  9.    * Database URL.
  10.    * Change this to restaurants.json file location on your server.
  11.    */
  12.   static get DATABASE_URL() {
  13.     const port = 1337; // Change this to your server port
  14.     return `http://localhost:${port}/restaurants`;
  15.   }
  16.  
  17.     /**
  18.      * Create DataBase
  19.      */
  20.  
  21.     static openDataBase(){
  22.       return idb.open('restaurantDb',1,function(upgradeDb){
  23.         upgradeDb.createObjectStore('restaurantDb',{
  24.           keyPath:'id'
  25.         });
  26.         });
  27.     }
  28.  
  29.     /**
  30.      * Saving on DataBase
  31.      */
  32.  
  33.     static saveDataBase(data){
  34.       return DBHelper.openDataBase().then(function (db){
  35.         if(!db) return;
  36.         let tx=db.transaction('restaurantDb','readwrite');
  37.         let store=tx.objectStore('restaurantDb');
  38.         data.forEach(function(restaurant){
  39.           store.put(restaurant);
  40.         });
  41.         return tx.complete;
  42.       });
  43.     }
  44.  
  45.     /**
  46.      * Getting data
  47.      */
  48.     static getCachedDb(){
  49.       dbpromise=DBHelper.openDataBase();
  50.       return dbpromise.then(function (db){
  51.         if(!db) return;
  52.         let tx=db.transaction('restaurantDb');
  53.         let store=tx.objectStore('restaurantDb');
  54.         return store.getAll();
  55.       });
  56.     }
  57.  
  58.     static fromAPI(){
  59.       return fetch(DBHelper.DATABASE_URL).then(function (response) {
  60.         return response.json();
  61.  
  62.       }).then(restaurants=>{
  63.         DBHelper.saveDataBase(restaurants);
  64.         return restaurants;
  65.       });
  66.     }
  67.  
  68.     /**
  69.    * Fetch all restaurants.
  70.    */
  71.    static fetchRestaurants(callback) {
  72.      fetch(DBHelper.DATABASE_URL)
  73.      .then(function(response){
  74.         return response.json();
  75.      })
  76.      .then(function(response){
  77.        callback(null,response);
  78.        console.log('Sucess:',response);
  79.      })
  80.    }
  81.   /**
  82.    * Fetch a restaurant by its ID.
  83.    */
  84.   static fetchRestaurantById(id, callback) {
  85.     // fetch all restaurants with proper error handling.
  86.     DBHelper.fetchRestaurants((error, restaurants) => {
  87.       if (error) {
  88.         callback(error, null);
  89.       } else {
  90.         const restaurant = restaurants.find(r => r.id == id);
  91.         if (restaurant) { // Got the restaurant
  92.           callback(null, restaurant);
  93.         } else { // Restaurant does not exist in the database
  94.           callback('Restaurant does not exist', null);
  95.         }
  96.       }
  97.     });
  98.   }
  99.  
  100.   /**
  101.    * Fetch restaurants by a cuisine type with proper error handling.
  102.    */
  103.   static fetchRestaurantByCuisine(cuisine, callback) {
  104.     // Fetch all restaurants  with proper error handling
  105.     DBHelper.fetchRestaurants((error, restaurants) => {
  106.       if (error) {
  107.         callback(error, null);
  108.       } else {
  109.         // Filter restaurants to have only given cuisine type
  110.         const results = restaurants.filter(r => r.cuisine_type == cuisine);
  111.         callback(null, results);
  112.       }
  113.     });
  114.   }
  115.  
  116.   /**
  117.    * Fetch restaurants by a neighborhood with proper error handling.
  118.    */
  119.    static fetchRestaurantByCuisine(cuisine, callback) {
  120.      // Fetch all restaurants  with proper error handling
  121.      DBHelper.fetchRestaurants((error, restaurants) => {
  122.        if (error) {
  123.          callback(error, null);
  124.        } else {
  125.          // Filter restaurants to have only given cuisine type
  126.          const results = restaurants.filter(r => r.cuisine_type == cuisine);
  127.          callback(null, results);
  128.        }
  129.      });
  130.    }
  131.  
  132.    /**
  133.     * Fetch restaurants by a cuisine and a neighborhood with proper error handling.
  134.     */
  135.    static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) {
  136.      // Fetch all restaurants
  137.      DBHelper.fetchRestaurants((error, restaurants) => {
  138.        if (error) {
  139.          callback(error, null);
  140.        } else {
  141.          let results = restaurants
  142.          if (cuisine != 'all') { // filter by cuisine
  143.            results = results.filter(r => r.cuisine_type == cuisine);
  144.          }
  145.          if (neighborhood != 'all') { // filter by neighborhood
  146.            results = results.filter(r => r.neighborhood == neighborhood);
  147.          }
  148.          callback(null, results);
  149.        }
  150.      });
  151.    }
  152.  
  153.  
  154.   /**
  155.    * Fetch all neighborhoods with proper error handling.
  156.    */
  157.   static fetchNeighborhoods(callback) {
  158.     // Fetch all restaurants
  159.     DBHelper.fetchRestaurants((error, restaurants) => {
  160.       if (error) {
  161.         callback(error, null);
  162.       } else {
  163.         // Get all neighborhoods from all restaurants
  164.         const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)
  165.         // Remove duplicates from neighborhoods
  166.         const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)
  167.         callback(null, uniqueNeighborhoods);
  168.       }
  169.     });
  170.   }
  171.  
  172.   /**
  173.    * Fetch all cuisines with proper error handling.
  174.    */
  175.   static fetchCuisines(callback) {
  176.     // Fetch all restaurants
  177.     DBHelper.fetchRestaurants((error, restaurants) => {
  178.       if (error) {
  179.         callback(error, null);
  180.       } else {
  181.         // Get all cuisines from all restaurants
  182.         const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type)
  183.         // Remove duplicates from cuisines
  184.         const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i)
  185.         callback(null, uniqueCuisines);
  186.       }
  187.     });
  188.   }
  189.  
  190.   /**
  191.    * Restaurant page URL.
  192.    */
  193.   static urlForRestaurant(restaurant) {
  194.     return (`./restaurant.html?id=${restaurant.id}`);
  195.   }
  196.  
  197.   /**
  198.    * Restaurant image URL.
  199.    */
  200.   static imageUrlForRestaurant(restaurant) {
  201.     return (`./img/${restaurant.id}`);
  202.   }
  203.  
  204.   /**
  205.    * Map marker for a restaurant.
  206.    */
  207. static mapMarkerForRestaurant(restaurant, map) {
  208.         // https://leafletjs.com/reference-1.3.0.html#marker
  209.         const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng], {
  210.             title: restaurant.name,
  211.             alt: restaurant.name,
  212.             url: DBHelper.urlForRestaurant(restaurant)
  213.         })
  214.         marker.addTo(newMap);
  215.         return marker;
  216.     }
  217.  
  218. }
Advertisement
Add Comment
Please, Sign In to add comment