-
Notifications
You must be signed in to change notification settings - Fork 55
/
useAuthenticatedFetch.js
42 lines (38 loc) · 1.43 KB
/
useAuthenticatedFetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { authenticatedFetch } from "@shopify/app-bridge/utilities";
import { useAppBridge } from "@shopify/app-bridge-react";
import { Redirect } from "@shopify/app-bridge/actions";
/**
* A hook that returns an auth-aware fetch function.
* @desc The returned fetch function that matches the browser's fetch API
* See: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
* It will provide the following functionality:
*
* 1. Add a `X-Shopify-Access-Token` header to the request.
* 2. Check response for `X-Shopify-API-Request-Failure-Reauthorize` header.
* 3. Redirect the user to the reauthorization URL if the header is present.
*
* @returns {Function} fetch function
*/
export function useAuthenticatedFetch() {
const app = useAppBridge();
const fetchFunction = authenticatedFetch(app);
return async (uri, options) => {
const response = await fetchFunction(uri, options);
checkHeadersForReauthorization(response.headers, app);
return response;
};
}
function checkHeadersForReauthorization(headers, app) {
if (headers.get("X-Shopify-API-Request-Failure-Reauthorize") === "1") {
const authUrlHeader =
headers.get("X-Shopify-API-Request-Failure-Reauthorize-Url") ||
`/api/auth`;
const redirect = Redirect.create(app);
redirect.dispatch(
Redirect.Action.REMOTE,
authUrlHeader.startsWith("/")
? `https://${window.location.host}${authUrlHeader}`
: authUrlHeader,
);
}
}