|
| 1 | +/* |
| 2 | + * CloudBeaver - Cloud Database Manager |
| 3 | + * Copyright (C) 2020-2026 DBeaver Corp and others |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0. |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + */ |
| 8 | + |
| 9 | +export function submitForm(url: string, fields: Iterable<readonly [string, string]>): void { |
| 10 | + const form = document.createElement('form'); |
| 11 | + form.method = 'POST'; |
| 12 | + form.action = url; |
| 13 | + form.target = '_blank'; |
| 14 | + form.style.display = 'none'; |
| 15 | + |
| 16 | + for (const [name, value] of fields) { |
| 17 | + const input = document.createElement('input'); |
| 18 | + input.type = 'hidden'; |
| 19 | + input.name = name; |
| 20 | + input.value = value; |
| 21 | + form.appendChild(input); |
| 22 | + } |
| 23 | + |
| 24 | + document.body.appendChild(form); |
| 25 | + form.submit(); |
| 26 | + document.body.removeChild(form); |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * Flattens an object into form-encoded key/value pairs, skipping falsy values: |
| 31 | + * - arrays become repeated fields (`key=v1&key=v2`) |
| 32 | + * - nested objects are flattened — their inner keys become top-level fields (!collision of inner keys is not handled) |
| 33 | + */ |
| 34 | +export function objectToFormFields(obj: Record<string, unknown>): Array<[string, string]> { |
| 35 | + const fields: Array<[string, string]> = []; |
| 36 | + for (const [key, value] of Object.entries(obj)) { |
| 37 | + appendField(fields, key, value); |
| 38 | + } |
| 39 | + return fields; |
| 40 | +} |
| 41 | + |
| 42 | +function appendField(fields: Array<[string, string]>, key: string, value: unknown): void { |
| 43 | + if (value == null || value === '') { |
| 44 | + return; |
| 45 | + } |
| 46 | + if (Array.isArray(value)) { |
| 47 | + for (const item of value) { |
| 48 | + if (item != null && item !== '') { |
| 49 | + fields.push([key, String(item)]); |
| 50 | + } |
| 51 | + } |
| 52 | + return; |
| 53 | + } |
| 54 | + if (typeof value === 'object') { |
| 55 | + for (const [innerKey, innerValue] of Object.entries(value)) { |
| 56 | + appendField(fields, innerKey, innerValue); |
| 57 | + } |
| 58 | + return; |
| 59 | + } |
| 60 | + fields.push([key, String(value)]); |
| 61 | +} |
0 commit comments