Add api.fetchOptions to allow customising fetch() behaviour

This allows sending custom HTTP headers or including cookies in the
request!
This commit is contained in:
Linus Groh
2020-05-09 15:40:50 +01:00
parent 6b1d35be51
commit 2c4ead262a
3 changed files with 27 additions and 1 deletions

View File

@@ -24,6 +24,7 @@ window.owntracks.config = {};
- `api`
- [`baseUrl`](#apibaseurl)
- [`fetchOptions`](#apifetchoptions)
- [`endDateTime`](#enddatetime)
- [`ignorePingLocation`](#ignorepinglocation)
- [`locale`](#locale)
@@ -89,6 +90,26 @@ Base URL for the recorder's HTTP and WebSocket API. Keep CORS in mind.
};
```
### `api.fetchOptions`
Options for API requests (made with `fetch()`). See [`fetch()` docs on MDN] for details.
You can use this for example to send custom HTTP headers or to include cookies in the request.
- Type: [`Object`]
- Default: `{}`
- Example:
```js
// Include credentials (e.g. cookies)
window.owntracks.config = {
api: {
fetchOptions: {
credentials: "include"
}
}
};
```
### `endDateTime`
Initial end date and time (browser timezone) for fetched data.
@@ -458,3 +479,4 @@ Whether to enable verbose mode or not.
[`object`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
[`string`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
[css `<color>`]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
[`fetch()` docs on MDN]: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters

View File

@@ -1,3 +1,4 @@
import config from "@/config";
import { log, logLevels } from "@/logging";
import { getApiUrl, getLocationHistoryCount } from "@/util";
@@ -12,7 +13,9 @@ const fetchApi = (path, params = {}) => {
const url = getApiUrl(path);
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
log("HTTP", `GET ${url.href}`);
return fetch(url.href).catch(error => log("HTTP", error, logLevels.ERROR));
return fetch(url.href, config.api.fetchOptions).catch(error =>
log("HTTP", error, logLevels.ERROR)
);
};
/**

View File

@@ -10,6 +10,7 @@ startDateTime.setHours(0, 0, 0, 0);
const DEFAULT_CONFIG = {
api: {
baseUrl: `${window.location.protocol}//${window.location.host}`,
fetchOptions: {},
},
endDateTime,
ignorePingLocation: true,