瀏覽代碼

refactor: include PeerJS version in HTTP requests

This allows us to observe how fast a new version is rolled out
Jonas Gloning 3 年之前
父節點
當前提交
4a7dba0e4e
共有 3 個文件被更改,包括 19 次插入24 次删除
  1. 16 23
      lib/api.ts
  2. 2 1
      lib/socket.ts
  3. 1 0
      tsconfig.json

+ 16 - 23
lib/api.ts

@@ -1,32 +1,27 @@
 import { util } from "./util";
 import logger from "./logger";
+import { PeerJSOption } from "./optionInterfaces";
+import { version } from "../package.json";
 
 export class API {
-	constructor(private readonly _options: any) {}
-
-	private _buildUrl(method: string): string {
-		const protocol = this._options.secure ? "https://" : "http://";
-		let url =
-			protocol +
-			this._options.host +
-			":" +
-			this._options.port +
-			this._options.path +
-			this._options.key +
-			"/" +
-			method;
-		const queryString = "?ts=" + new Date().getTime() + "" + Math.random();
-		url += queryString;
-
-		return url;
+	constructor(private readonly _options: PeerJSOption) {}
+
+	private _buildRequest(method: string): Promise<Response> {
+		const protocol = this._options.secure ? "https" : "http";
+		const { host, port, path, key } = this._options;
+		const url = new URL(`${protocol}://${host}:${port}${path}${key}/${method}`);
+		// TODO: Why timestamp, why random?
+		url.searchParams.set("ts", `${Date.now()}${Math.random()}`);
+		url.searchParams.set("version", version);
+		return fetch(url.href, {
+			referrerPolicy: "strict-origin-when-cross-origin",
+		});
 	}
 
 	/** Get a unique ID from the server via XHR and initialize with it. */
 	async retrieveId(): Promise<string> {
-		const url = this._buildUrl("id");
-
 		try {
-			const response = await fetch(url);
+			const response = await this._buildRequest("id");
 
 			if (response.status !== 200) {
 				throw new Error(`Error. Status:${response.status}`);
@@ -54,10 +49,8 @@ export class API {
 
 	/** @deprecated */
 	async listAllPeers(): Promise<any[]> {
-		const url = this._buildUrl("peers");
-
 		try {
-			const response = await fetch(url);
+			const response = await this._buildRequest("peers");
 
 			if (response.status !== 200) {
 				if (response.status === 401) {

+ 2 - 1
lib/socket.ts

@@ -1,6 +1,7 @@
 import { EventEmitter } from "eventemitter3";
 import logger from "./logger";
 import { SocketEventType, ServerMessageType } from "./enums";
+import { version } from "../package.json";
 
 /**
  * An abstraction on top of WebSockets to provide fastest
@@ -38,7 +39,7 @@ export class Socket extends EventEmitter {
 			return;
 		}
 
-		this._socket = new WebSocket(wsUrl);
+		this._socket = new WebSocket(wsUrl + "?version=" + version);
 		this._disconnected = false;
 
 		this._socket.onmessage = (event) => {

+ 1 - 0
tsconfig.json

@@ -7,6 +7,7 @@
 		"noUnusedParameters": true,
 		"skipLibCheck": true,
 		"isolatedModules": true,
+		"resolveJsonModule": true,
 		"lib": ["es2020", "dom"]
 	}
 }