-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
SITES-18113: Extensibility template improvements
- Loading branch information
1 parent
58eccd3
commit 808758a
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
/* | ||
* <license header> | ||
*/ | ||
|
||
/* global fetch */ | ||
|
||
/** | ||
* | ||
* Invokes a web action | ||
* | ||
* @param {string} actionUrl | ||
* @param {object} headers | ||
* @param {object} params | ||
* | ||
* @returns {Promise<string|object>} the response | ||
* | ||
*/ | ||
|
||
async function actionWebInvoke (actionUrl, headers = {}, params = {}, options = { method: 'POST' }) { | ||
const actionHeaders = { | ||
'Content-Type': 'application/json', | ||
...headers | ||
} | ||
|
||
const fetchConfig = { | ||
headers: actionHeaders | ||
} | ||
|
||
if (window.location.hostname === 'localhost') { | ||
actionHeaders['x-ow-extra-logging'] = 'on' | ||
} | ||
|
||
fetchConfig.method = options.method.toUpperCase() | ||
|
||
if (fetchConfig.method === 'GET') { | ||
actionUrl = new URL(actionUrl) | ||
Object.keys(params).forEach(key => actionUrl.searchParams.append(key, params[key])) | ||
} else if (fetchConfig.method === 'POST') { | ||
fetchConfig.body = JSON.stringify(params) | ||
} | ||
|
||
const response = await fetch(actionUrl, fetchConfig) | ||
|
||
let content = await response.text() | ||
|
||
if (!response.ok) { | ||
return JSON.parse(content) | ||
} | ||
try { | ||
content = JSON.parse(content) | ||
} catch (e) { | ||
// response is not json | ||
} | ||
return content | ||
} | ||
|
||
export default actionWebInvoke |