api.ts 2.4 KB

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