ソースを参照

replace xhr to fetch in api

afrokick 6 年 前
コミット
a2da2e4488
2 ファイル変更63 行追加104 行削除
  1. 46 79
      lib/api.ts
  2. 17 25
      lib/peer.ts

+ 46 - 79
lib/api.ts

@@ -1,12 +1,8 @@
 import { util } from "./util";
 import { PeerErrorType, PeerEventType } from "./enums";
 
-export class ApiError {
-  type: PeerErrorType;
-  message: string = "";
-}
 export class API {
-  constructor(private readonly _options: any) {}
+  constructor(private readonly _options: any) { }
 
   private _buildUrl(method: string): string {
     const protocol = this._options.secure ? "https://" : "http://";
@@ -26,21 +22,25 @@ export class API {
   }
 
   /** Get a unique ID from the server via XHR and initialize with it. */
-  retrieveId(cb = (error: ApiError, id?: string) => {}): void {
-    const http = new XMLHttpRequest();
+  async retrieveId(): Promise<string> {
     const url = this._buildUrl("id");
-    // If there's no ID we need to wait for one before trying to init socket.
-    http.open("get", url, true);
 
-    const self = this;
+    try {
+      const response = await fetch(url);
+
+      if (response.status !== 200) {
+        throw new Error(`Error. Status:${response.status}`)
+      }
+
+      return response.text();
+    } catch (error) {
+      util.error("Error retrieving ID", error);
 
-    http.onerror = function(e) {
-      util.error("Error retrieving ID", e);
       let pathError = "";
 
       if (
-        self._options.path === "/" &&
-        self._options.host !== util.CLOUD_HOST
+        this._options.path === "/" &&
+        this._options.host !== util.CLOUD_HOST
       ) {
         pathError =
           " If you passed in a `path` to your self-hosted PeerServer, " +
@@ -48,76 +48,43 @@ export class API {
           "Peer.";
       }
 
-      cb({
-        type: PeerErrorType.ServerError,
-        message: "Could not get an ID from the server." + pathError
-      });
-    };
-
-    http.onreadystatechange = function() {
-      if (http.readyState !== 4 || http.status === 0) {
-        return;
-      }
-
-      if (http.status !== 200) {
-        http.onerror(new ProgressEvent(`status === ${http.status}`));
-        return;
-      }
-
-      cb(null, http.responseText);
-    };
-
-    http.send(null);
+      throw new Error("Could not get an ID from the server." + pathError);
+    }
   }
 
-  listAllPeers(cb = (error: ApiError, peers?: any[]) => {}): void {
-    const http = new XMLHttpRequest();
-    let url = this._buildUrl("peers");
-
-    // If there's no ID we need to wait for one before trying to init socket.
-    http.open("get", url, true);
-
-    const self = this;
-
-    http.onerror = function(e) {
-      util.error("Error retrieving list of peers", e);
-
-      cb({
-        type: PeerErrorType.ServerError,
-        message: "Could not get peers from the server."
-      });
-    };
-
-    http.onreadystatechange = function() {
-      if (http.readyState !== 4) {
-        return;
-      }
-
-      if (http.status === 401) {
-        let helpfulError = "";
-        if (self._options.host !== util.CLOUD_HOST) {
-          helpfulError =
-            "It looks like you're using the cloud server. You can email " +
-            "team@peerjs.com to enable peer listing for your API key.";
-        } else {
-          helpfulError =
-            "You need to enable `allow_discovery` on your self-hosted " +
-            "PeerServer to use this feature.";
+  /** @deprecated */
+  async listAllPeers(): Promise<any[]> {
+    const url = this._buildUrl("peers");
+
+    try {
+      const response = await fetch(url);
+
+      if (response.status !== 200) {
+        if (response.status === 401) {
+          let helpfulError = "";
+
+          if (this._options.host === util.CLOUD_HOST) {
+            helpfulError =
+              "It looks like you're using the cloud server. You can email " +
+              "team@peerjs.com to enable peer listing for your API key.";
+          } else {
+            helpfulError =
+              "You need to enable `allow_discovery` on your self-hosted " +
+              "PeerServer to use this feature.";
+          }
+
+          throw new Error("It doesn't look like you have permission to list peers IDs. " +
+            helpfulError);
         }
 
-        cb({
-          type: PeerErrorType.ServerError,
-          message:
-            "It doesn't look like you have permission to list peers IDs. " +
-            helpfulError
-        });
-      } else if (http.status !== 200) {
-        cb(null, []);
-      } else {
-        cb(JSON.parse(http.responseText));
+        throw new Error(`Error. Status:${response.status}`)
       }
-    };
 
-    http.send(null);
+      return response.json();
+    } catch (error) {
+      util.error("Error retrieving list peers", error);
+
+      throw new Error("Could not get list peers from the server." + error);
+    }
   }
 }

+ 17 - 25
lib/peer.ts

@@ -148,13 +148,9 @@ export class Peer extends EventEmitter {
     if (id) {
       this._initialize(id);
     } else {
-      this._api.retrieveId((error, id) => {
-        if (error) {
-          return this._abort(error.type, error.message);
-        }
-
-        this._initialize(id);
-      });
+      this._api.retrieveId()
+        .then(id => this._initialize(id))
+        .catch(error => this._abort(PeerErrorType.ServerError, error));
     }
   }
 
@@ -188,7 +184,7 @@ export class Peer extends EventEmitter {
       }
     });
 
-    this.socket.on(SocketEventType.Close, function() {
+    this.socket.on(SocketEventType.Close, function () {
       // If we haven't explicitly disconnected, emit error.
       if (!self.disconnected) {
         self._abort(
@@ -338,9 +334,9 @@ export class Peer extends EventEmitter {
     if (this.disconnected) {
       util.warn(
         "You cannot connect to a new Peer because you called " +
-          ".disconnect() on this Peer and ended your connection with the " +
-          "server. You can create a new Peer to reconnect, or call reconnect " +
-          "on this peer if you believe its ID to still be available."
+        ".disconnect() on this Peer and ended your connection with the " +
+        "server. You can create a new Peer to reconnect, or call reconnect " +
+        "on this peer if you believe its ID to still be available."
       );
       this.emitError(
         PeerErrorType.Disconnected,
@@ -362,8 +358,8 @@ export class Peer extends EventEmitter {
     if (this.disconnected) {
       util.warn(
         "You cannot connect to a new Peer because you called " +
-          ".disconnect() on this Peer and ended your connection with the " +
-          "server. You can create a new Peer to reconnect."
+        ".disconnect() on this Peer and ended your connection with the " +
+        "server. You can create a new Peer to reconnect."
       );
       this.emitError(
         PeerErrorType.Disconnected,
@@ -417,7 +413,7 @@ export class Peer extends EventEmitter {
 
   private _delayedAbort(type: PeerErrorType, message): void {
     const self = this;
-    util.setZeroTimeout(function() {
+    util.setZeroTimeout(function () {
       self._abort(type, message);
     });
   }
@@ -495,7 +491,7 @@ export class Peer extends EventEmitter {
    */
   disconnect(): void {
     const self = this;
-    util.setZeroTimeout(function() {
+    util.setZeroTimeout(function () {
       if (!self.disconnected) {
         self._disconnected = true;
         self._open = false;
@@ -531,8 +527,8 @@ export class Peer extends EventEmitter {
     } else {
       throw new Error(
         "Peer " +
-          this.id +
-          " cannot reconnect because it is not disconnected from the server!"
+        this.id +
+        " cannot reconnect because it is not disconnected from the server!"
       );
     }
   }
@@ -543,13 +539,9 @@ export class Peer extends EventEmitter {
    * the cloud server, email team@peerjs.com to get the functionality enabled for
    * your key.
    */
-  listAllPeers(cb = (arg: any[]) => {}): void {
-    this._api.listAllPeers((error, peers) => {
-      if (error) {
-        return this._abort(error.type, error.message);
-      }
-
-      cb(peers);
-    });
+  listAllPeers(cb = (arg: any[]) => { }): void {
+    this._api.listAllPeers()
+      .then(peers => cb(peers))
+      .catch(error => this._abort(PeerErrorType.ServerError, error));
   }
 }