|
| 1 | +/** |
| 2 | + * Acquires all data from the given form and POSTs it as JSON to the target URL. |
| 3 | + * In case of failure this function will throw an error. |
| 4 | + * In case of success a parsed JSON body of the response will be returned, |
| 5 | + * unless the body contains a `location` field, |
| 6 | + * in that case the page will be redirected to that location. |
| 7 | + * |
| 8 | + * @param formId - ID of the form. |
| 9 | + * @param target - Target URL to POST to. Defaults to the current URL. |
| 10 | + * @returns {Promise<unknown>} - The response JSON. |
| 11 | + */ |
| 12 | +async function postJsonForm(formId, target = '') { |
| 13 | + const form = document.getElementById(formId); |
| 14 | + const formData = new FormData(form); |
| 15 | + const res = await fetch(target, { |
| 16 | + method: 'POST', |
| 17 | + credentials: 'include', |
| 18 | + headers: { 'accept': 'application/json', 'content-type': 'application/json' }, |
| 19 | + body: JSON.stringify(Object.fromEntries(formData)), |
| 20 | + }); |
| 21 | + if (res.status >= 400) { |
| 22 | + const error = await res.json(); |
| 23 | + throw new Error(`${error.statusCode} - ${error.name}: ${error.message}`) |
| 24 | + } else if (res.status === 200 || res.status === 201) { |
| 25 | + const body = await res.json(); |
| 26 | + if (body.location) { |
| 27 | + location.href = body.location; |
| 28 | + } else { |
| 29 | + return body; |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Redirects the page to the given target with the key/value pairs of the JSON body as query parameters. |
| 36 | + * Controls will be deleted from the JSON to prevent very large URLs. |
| 37 | + * `false` values will be deleted to prevent incorrect serializations to "false". |
| 38 | + * @param json - JSON to convert. |
| 39 | + * @param target - URL to redirect to. |
| 40 | + */ |
| 41 | +function redirectJsonResponse(json, target) { |
| 42 | + // These would cause the URL to get very large, can be acquired later if needed |
| 43 | + delete json.controls; |
| 44 | + |
| 45 | + // Remove false parameters since these would be converted to "false" strings |
| 46 | + for (const [key, val] of Object.entries(json)) { |
| 47 | + if (typeof val === 'boolean' && !val) { |
| 48 | + delete json[key]; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + const searchParams = new URLSearchParams(Object.entries(json)); |
| 53 | + location.href = `${target}?${searchParams.toString()}`; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Adds a listener to the given form to catch the form submission and do an API call instead. |
| 58 | + * In case of an error, the inner text of the given error block will be updated with the message. |
| 59 | + * In case of success the callback function will be called. |
| 60 | + * |
| 61 | + * @param formId - ID of the form. |
| 62 | + * @param errorId - ID of the error block. |
| 63 | + * @param apiTarget - Target URL to send the POST request to. Defaults to the current URL. |
| 64 | + * @param callback - Callback function that will be called with the response JSON. |
| 65 | + */ |
| 66 | +async function addPostListener(formId, errorId, apiTarget, callback) { |
| 67 | + const form = document.getElementById(formId); |
| 68 | + const errorBlock = document.getElementById(errorId); |
| 69 | + |
| 70 | + form.addEventListener('submit', async(event) => { |
| 71 | + event.preventDefault(); |
| 72 | + |
| 73 | + try { |
| 74 | + const json = await postJsonForm(formId, apiTarget); |
| 75 | + callback(json); |
| 76 | + } catch (error) { |
| 77 | + errorBlock.innerText = error.message; |
| 78 | + } |
| 79 | + }); |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * Updates links on a page based on the controls received from the API. |
| 84 | + * @param url - API URL that will return the controls |
| 85 | + * @param controlMap - Key/value map with keys being element IDs and values being the control field names. |
| 86 | + */ |
| 87 | +async function addControlLinks(url, controlMap) { |
| 88 | + const json = await fetchJson(url); |
| 89 | + for (let [ id, control ] of Object.entries(controlMap)) { |
| 90 | + updateElement(id, json.controls[control], { href: true }); |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +/** |
| 95 | + * Shows or hides the given element. |
| 96 | + * @param id - ID of the element. |
| 97 | + * @param visible - If it should be visible. |
| 98 | + */ |
| 99 | +function setVisibility(id, visible) { |
| 100 | + const element = document.getElementById(id); |
| 101 | + element.classList[visible ? 'remove' : 'add']('hidden'); |
| 102 | + // Disable children of hidden elements, |
| 103 | + // such that the browser does not expect input for them |
| 104 | + for (const child of getDescendants(element)) { |
| 105 | + if ('disabled' in child) |
| 106 | + child.disabled = !visible; |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +/** |
| 111 | + * Obtains all children, grandchildren, etc. of the given element. |
| 112 | + * @param element - Element to get all descendants from. |
| 113 | + */ |
| 114 | +function getDescendants(element) { |
| 115 | + return [...element.querySelectorAll("*")]; |
| 116 | +} |
| 117 | + |
| 118 | +/** |
| 119 | + * Updates the inner text and href field of an element. |
| 120 | + * @param id - ID of the element. |
| 121 | + * @param text - Text to put in the field(s). |
| 122 | + * @param options - Indicates which fields should be updated. |
| 123 | + * Keys should be `innerText` and/or `href`, values should be booleans. |
| 124 | + */ |
| 125 | +function updateElement(id, text, options) { |
| 126 | + const element = document.getElementById(id); |
| 127 | + if (options.innerText) { |
| 128 | + element.innerText = text; |
| 129 | + } |
| 130 | + if (options.href) { |
| 131 | + element.href = text; |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +/** |
| 136 | + * Fetches JSON from the url and converts it to an object. |
| 137 | + * @param url - URL to fetch JSON from. |
| 138 | + */ |
| 139 | +async function fetchJson(url) { |
| 140 | + const res = await fetch(url, { headers: { accept: 'application/json' } }); |
| 141 | + return res.json(); |
| 142 | +} |
0 commit comments