summaryrefslogtreecommitdiff
path: root/hooks/authenticatedFetch.js
blob: 4b57ff7fc3920590e0129ccc5805b0779ad55953 (plain)
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
function authenticatedFetch(uri, options) {
	var AppBridge = window['app-bridge'];
	var app = AppBridge.createApp({
		apiKey: '',
		host: ''
	});
	var fetchFunction = window['app-bridge-utils'].authenticatedFetch(app);
	return async (uri, options) => {
		var response = await fetchFunction(uri, options);
		var headers = response.headers;
		if (headers.get("X-Shopify-API-Request-Failure-Reauthorize")
			=== "1") {
			var authUrlHeader = headers.get(
				"X-Shopify-API-Request-Failure-Reauthorize-Url")
				|| `/api/auth`;
			var Redirect = AppBridge.actions.Redirect;
			Redirect.create(app).dispatch(Redirect.Action.REMOTE,
				authUrlHeader.startsWith("/")
				? `https://${window.location.host}${authUrlHeader}`
				: authUrlHeader
			);
		}
		return response;
	};
}