diff --git a/src/templates/web/src/utils.js b/src/templates/web/src/utils.js new file mode 100644 index 0000000..a70675b --- /dev/null +++ b/src/templates/web/src/utils.js @@ -0,0 +1,57 @@ +/* +* +*/ + +/* global fetch */ + +/** + * + * Invokes a web action + * + * @param {string} actionUrl + * @param {object} headers + * @param {object} params + * + * @returns {Promise} 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