Skip to content

Commit

Permalink
SITES-18113: Extensibility template improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
VladimirZaets committed Mar 14, 2024
1 parent 58eccd3 commit 808758a
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/templates/web/src/utils.js
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

0 comments on commit 808758a

Please sign in to comment.