api.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { util } from "./util";
  2. import logger from "./logger";
  3. export class API {
  4. constructor(private readonly _options: any) { }
  5. private _buildUrl(method: string): string {
  6. const protocol = this._options.secure ? "https://" : "http://";
  7. let url =
  8. protocol +
  9. this._options.host +
  10. ":" +
  11. this._options.port +
  12. this._options.path +
  13. this._options.key +
  14. "/" +
  15. method;
  16. const queryString = "?ts=" + new Date().getTime() + "" + Math.random();
  17. url += queryString;
  18. return url;
  19. }
  20. /** Get a unique ID from the server via XHR and initialize with it. */
  21. async retrieveId(): Promise<string> {
  22. const url = this._buildUrl("id");
  23. try {
  24. const response = await fetch(url);
  25. if (response.status !== 200) {
  26. throw new Error(`Error. Status:${response.status}`);
  27. }
  28. return response.text();
  29. } catch (error) {
  30. logger.error("Error retrieving ID", error);
  31. let pathError = "";
  32. if (
  33. this._options.path === "/" &&
  34. this._options.host !== util.CLOUD_HOST
  35. ) {
  36. pathError =
  37. " If you passed in a `path` to your self-hosted PeerServer, " +
  38. "you'll also need to pass in that same path when creating a new " +
  39. "Peer.";
  40. }
  41. throw new Error("Could not get an ID from the server." + pathError);
  42. }
  43. }
  44. /** @deprecated */
  45. async listAllPeers(): Promise<any[]> {
  46. const url = this._buildUrl("peers");
  47. try {
  48. const response = await fetch(url);
  49. if (response.status !== 200) {
  50. if (response.status === 401) {
  51. let helpfulError = "";
  52. if (this._options.host === util.CLOUD_HOST) {
  53. helpfulError =
  54. "It looks like you're using the cloud server. You can email " +
  55. "team@peerjs.com to enable peer listing for your API key.";
  56. } else {
  57. helpfulError =
  58. "You need to enable `allow_discovery` on your self-hosted " +
  59. "PeerServer to use this feature.";
  60. }
  61. throw new Error("It doesn't look like you have permission to list peers IDs. " +
  62. helpfulError);
  63. }
  64. throw new Error(`Error. Status:${response.status}`);
  65. }
  66. return response.json();
  67. } catch (error) {
  68. logger.error("Error retrieving list peers", error);
  69. throw new Error("Could not get list peers from the server." + error);
  70. }
  71. }
  72. }