Просмотр исходного кода

feat: allow API urls without protocol (use protocol of origin)

Fela Maslen 5 лет назад
Родитель
Сommit
33a313418c
2 измененных файлов с 10 добавлено и 4 удалено
  1. 5 3
      gmus-web/src/utils/url.spec.ts
  2. 5 1
      gmus-web/src/utils/url.ts

+ 5 - 3
gmus-web/src/utils/url.spec.ts

@@ -7,13 +7,15 @@ describe(getPubsubUrl.name, () => {
   });
 
   describe.each`
-    case             | apiUrl                     | testCase          | expectedPubsubUrl
-    ${'is https'}    | ${'https://some.api:1876'} | ${'a secure URL'} | ${'wss://some.api:1876/pubsub'}
-    ${'has no port'} | ${'http://some.api'}       | ${'no port'}      | ${'ws://some.api/pubsub'}
+    case                 | apiUrl                     | testCase          | expectedPubsubUrl
+    ${'is https'}        | ${'https://some.api:1876'} | ${'a secure URL'} | ${'wss://some.api:1876/pubsub'}
+    ${'has no port'}     | ${'http://some.api'}       | ${'no port'}      | ${'ws://some.api/pubsub'}
+    ${'has no protocol'} | ${'//some.api'}            | ${'no protocol'}  | ${'ws://some.api/pubsub'}
   `('when the URL $case', ({ testCase, apiUrl, expectedPubsubUrl }) => {
     const envBefore = process.env.REACT_APP_API_URL;
     beforeAll(() => {
       process.env.REACT_APP_API_URL = apiUrl;
+      window.location.protocol = 'http:';
     });
     afterAll(() => {
       process.env.REACT_APP_API_URL = envBefore;

+ 5 - 1
gmus-web/src/utils/url.ts

@@ -1,5 +1,9 @@
 export function getApiUrl(): string {
-  return process.env.REACT_APP_API_URL ?? 'http://localhost:3000';
+  const baseUrl = process.env.REACT_APP_API_URL ?? 'http://localhost:3000';
+  if (baseUrl.startsWith('//')) {
+    return `${window.location.protocol}${baseUrl}`;
+  }
+  return baseUrl;
 }
 
 export function getPubsubUrl(): string {