'use strict'

/**
 * Dependencies
 */
const fetch = require('node-fetch')

/**
 * Cache
 * 
 * @class
 * Cache for JSON Schema remote reference resolution.
 */
class RemoteCache {

  /**
   * Constructor
   */
  constructor () {
    this.cache = {}
  }

  /**
   * Resolve
   *
   * @description
   * Get schema from cache. If the schema is not present on the cache then
   * fetch it from the remote location and store it on the cache.
   *
   * @todo
   * This needs to be a little more sophisticated... ideally some sort of
   * timeout is needed.
   *
   * @param {uri} uri - URI of the remote schema reference
   */
  resolve (uri) {
    return new Promise((resolve, reject) => {

      if (this.cache[uri]) {
        return resolve(this.cache[uri])
      } else {
        return fetch(uri)
          .then(res => {
            return res.json()
          })
          .then(json => {
            return resolve(json)
          })
          .catch(reject)
      }

    })
  }

}

/**
 * Export
 */
module.exports = new RemoteCache()

@@ -636,57 +636,8 @@
 ) %7B%0A
-    return new Promise((resolve, reject) =%3E %7B%0A%0A  
     
@@ -659,18 +659,16 @@
 uri%5D) %7B%0A
-  
       re
@@ -705,23 +705,11 @@
     
-  %7D else %7B%0A    
+%7D%0A%0A
     
@@ -728,28 +728,24 @@
 (uri)%0A      
-  
-  
 .then(res =%3E
@@ -743,28 +743,24 @@
 en(res =%3E %7B%0A
-    
         retu
@@ -775,35 +775,27 @@
 son()%0A      
-   
- 
 %7D)%0A
-    
       .then(
@@ -816,32 +816,30 @@
     
-    return resolve(
+this.cache%5Buri%5D = 
 json
-)
 %0A   
@@ -847,47 +847,22 @@
     
-  %7D)%0A          .catch(reject)%0A      %7D%0A%0A
+return json%0A  
     

remove promise wrapper and add fetched results to cache