Ver Fonte

Merge pull request #1369 from transloadit/async-token-storage

companion-client: add asyn wrapper around token storage
Ifedapo .A. Olarewaju há 6 anos atrás
pai
commit
fa6e5d7b02

+ 19 - 11
packages/@uppy/companion-client/src/Provider.js

@@ -1,6 +1,7 @@
 'use strict'
 
 const RequestClient = require('./RequestClient')
+const tokenStorage = require('./tokenStorage')
 
 const _getName = (id) => {
   return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
@@ -17,14 +18,18 @@ module.exports = class Provider extends RequestClient {
     this.tokenKey = `companion-${this.pluginId}-auth-token`
   }
 
-  get defaultHeaders () {
-    return Object.assign({}, super.defaultHeaders, {'uppy-auth-token': this.getAuthToken()})
+  headers () {
+    return new Promise((resolve, reject) => {
+      super.headers().then((headers) => {
+        this.getAuthToken().then((token) => {
+          resolve(Object.assign({}, headers, { 'uppy-auth-token': token }))
+        })
+      }).catch(reject)
+    })
   }
 
-  // @todo(i.olarewaju) consider whether or not this method should be exposed
   setAuthToken (token) {
-    // @todo(i.olarewaju) add fallback for OOM storage
-    this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token)
+    return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token)
   }
 
   getAuthToken () {
@@ -51,11 +56,14 @@ module.exports = class Provider extends RequestClient {
   }
 
   logout (redirect = location.href) {
-    return this.get(`${this.id}/logout?redirect=${redirect}`)
-      .then((res) => {
-        this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey)
-        return res
-      })
+    return new Promise((resolve, reject) => {
+      this.get(`${this.id}/logout?redirect=${redirect}`)
+        .then((res) => {
+          this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey)
+            .then(() => resolve(res))
+            .catch(reject)
+        }).catch(reject)
+    })
   }
 
   static initPlugin (plugin, opts, defaultOpts) {
@@ -81,6 +89,6 @@ module.exports = class Provider extends RequestClient {
       }
     }
 
-    plugin.storage = plugin.opts.storage || localStorage
+    plugin.storage = plugin.opts.storage || tokenStorage
   }
 }

+ 51 - 38
packages/@uppy/companion-client/src/RequestClient.js

@@ -25,8 +25,8 @@ module.exports = class RequestClient {
     }
   }
 
-  get headers () {
-    return Object.assign({}, this.defaultHeaders, this.opts.serverHeaders || {})
+  headers () {
+    return Promise.resolve(Object.assign({}, this.defaultHeaders, this.opts.serverHeaders || {}))
   }
 
   onReceiveResponse (response) {
@@ -53,50 +53,63 @@ module.exports = class RequestClient {
   }
 
   get (path) {
-    return fetch(this._getUrl(path), {
-      method: 'get',
-      headers: this.headers,
-      credentials: 'same-origin'
-    })
-      // @todo validate response status before calling json
-      .then(this.onReceiveResponse)
-      .then((res) => res.json())
-      .catch((err) => {
-        throw new Error(`Could not get ${this._getUrl(path)}. ${err}`)
+    return new Promise((resolve, reject) => {
+      this.headers().then((headers) => {
+        fetch(this._getUrl(path), {
+          method: 'get',
+          headers: headers,
+          credentials: 'same-origin'
+        })
+          // @todo validate response status before calling json
+          .then(this.onReceiveResponse)
+          .then((res) => res.json().then(resolve))
+          .catch((err) => {
+            reject(new Error(`Could not get ${this._getUrl(path)}. ${err}`))
+          })
       })
+    })
   }
 
   post (path, data) {
-    return fetch(this._getUrl(path), {
-      method: 'post',
-      headers: this.headers,
-      credentials: 'same-origin',
-      body: JSON.stringify(data)
-    })
-      .then(this.onReceiveResponse)
-      .then((res) => {
-        if (res.status < 200 || res.status > 300) {
-          throw new Error(`Could not post ${this._getUrl(path)}. ${res.statusText}`)
-        }
-        return res.json()
-      })
-      .catch((err) => {
-        throw new Error(`Could not post ${this._getUrl(path)}. ${err}`)
+    return new Promise((resolve, reject) => {
+      this.headers().then((headers) => {
+        fetch(this._getUrl(path), {
+          method: 'post',
+          headers: headers,
+          credentials: 'same-origin',
+          body: JSON.stringify(data)
+        })
+          .then(this.onReceiveResponse)
+          .then((res) => {
+            if (res.status < 200 || res.status > 300) {
+              reject(new Error(`Could not post ${this._getUrl(path)}. ${res.statusText}`))
+              return
+            }
+            res.json().then(resolve)
+          })
+          .catch((err) => {
+            reject(new Error(`Could not post ${this._getUrl(path)}. ${err}`))
+          })
       })
+    })
   }
 
   delete (path, data) {
-    return fetch(`${this.hostname}/${path}`, {
-      method: 'delete',
-      headers: this.headers,
-      credentials: 'same-origin',
-      body: data ? JSON.stringify(data) : null
-    })
-      .then(this.onReceiveResponse)
-      // @todo validate response status before calling json
-      .then((res) => res.json())
-      .catch((err) => {
-        throw new Error(`Could not delete ${this._getUrl(path)}. ${err}`)
+    return new Promise((resolve, reject) => {
+      this.headers().then((headers) => {
+        fetch(`${this.hostname}/${path}`, {
+          method: 'delete',
+          headers: headers,
+          credentials: 'same-origin',
+          body: data ? JSON.stringify(data) : null
+        })
+          .then(this.onReceiveResponse)
+          // @todo validate response status before calling json
+          .then((res) => res.json().then(resolve))
+          .catch((err) => {
+            reject(new Error(`Could not delete ${this._getUrl(path)}. ${err}`))
+          })
       })
+    })
   }
 }

+ 21 - 0
packages/@uppy/companion-client/src/tokenStorage.js

@@ -0,0 +1,21 @@
+'use strict'
+/**
+ * This module serves as an Async wrapper for LocalStorage
+ */
+module.exports.setItem = (key, value) => {
+  return new Promise((resolve) => {
+    localStorage.setItem(key, value)
+    resolve()
+  })
+}
+
+module.exports.getItem = (key) => {
+  return Promise.resolve(localStorage.getItem(key))
+}
+
+module.exports.removeItem = (key) => {
+  return new Promise((resolve) => {
+    localStorage.removeItem(key)
+    resolve()
+  })
+}