diff --git a/README.md b/README.md index c83bb1c..2f23d8b 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ Connecting your project to Cockpit is done by instantiating CockpitSDK. This obj | **webSocket** | Websocket address (if used) | | **fetchInitOptions** | [Init options](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) to apply on every Fetch request | | **defaultOptions** | Options to be applied on every Cockpit fetch | +| **authHeader** | Use the *Authorization* header instead of a query parameter|
defaultOptions:

diff --git a/src/CockpitSDK.js b/src/CockpitSDK.js index b031302..733f1d8 100644 --- a/src/CockpitSDK.js +++ b/src/CockpitSDK.js @@ -44,6 +44,7 @@ class CockpitSDK { host, lang, webSocket, + authHeader, apiEndpoints = {}, ...rest }) { @@ -55,7 +56,7 @@ class CockpitSDK { invalidConfig, '\n', 'Valid keys are:', - 'accessToken, defaultOptions, fetchInitOptions, host, lang, webSocket', + 'accessToken, defaultOptions, fetchInitOptions, host, lang, webSocket, authHeader', ); this.host = host; @@ -65,11 +66,15 @@ class CockpitSDK { this.endpoints = { ...this.defaultEndpoints, ...apiEndpoints }; this.accessToken = accessToken; this.webSocket = webSocket; + this.authHeader = authHeader; this.queryParams = { lang: this.lang, - token: this.accessToken, }; + if (!this.authHeader) { + this.queryParams.token = this.accessToken; + } + if (webSocket) { this.setWebsocket(webSocket); } @@ -81,11 +86,14 @@ class CockpitSDK { ...this.fetchInitOptions, }; - const hostWithToken = `${this.host}${apiPath}?${qs.stringify( + if (this.authHeader) { + requestInit.headers.Authorization = `Bearer ${this.accessToken}`; + } + const url = `${this.host}${apiPath}?${qs.stringify( this.queryParams, )}&${qs.stringify(queryParams)}`; - return fetch(hostWithToken, requestInit).then(x => x.json()); + return fetch(url, requestInit).then(x => x.json()); } // @param {string} apiPath diff --git a/src/__tests__/CockpitSDK.test.js b/src/__tests__/CockpitSDK.test.js index 28916bc..695d138 100644 --- a/src/__tests__/CockpitSDK.test.js +++ b/src/__tests__/CockpitSDK.test.js @@ -18,6 +18,25 @@ test('Expect Cockpit.image to return array of numbers', () => { ); }); +test('Expect Cockpit.image to return array of numbers and have the token in the header', () => { + const cockpit = new CockpitSDK({ + host: 'foo', + accessToken: 'bar', + lang: 'biz', + authHeader: true, + }); + const imageOptions = [10, 20, 30]; + + const result = cockpit.image('bux', imageOptions); + + expect(result).toBe( + '' + + 'foo/api/cockpit/image?d=1&lang=biz&o=1&src=bux&w=10 10w, ' + + 'foo/api/cockpit/image?d=1&lang=biz&o=1&src=bux&w=20 20w, ' + + 'foo/api/cockpit/image?d=1&lang=biz&o=1&src=bux&w=30 30w', + ); +}); + test('Expect Cockpit.image to return height', () => { const cockpit = new CockpitSDK({ host: 'foo',