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