mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 21:41:57 +00:00
46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
export function toFormData(
|
|
value: unknown,
|
|
form = new FormData(),
|
|
parentKey?: string
|
|
) {
|
|
if (value === undefined || value === null) {
|
|
if (parentKey) form.append(parentKey, '');
|
|
return form;
|
|
}
|
|
|
|
if (value instanceof File) {
|
|
if (!parentKey) throw new Error('File must have a key');
|
|
form.append(parentKey, value);
|
|
return form;
|
|
}
|
|
|
|
if (Array.isArray(value)) {
|
|
value.forEach((v, i) => {
|
|
const key = parentKey ? `${parentKey}[${i}]` : `${i}`;
|
|
toFormData(v, form, key);
|
|
});
|
|
return form;
|
|
}
|
|
|
|
if (typeof value === 'object') {
|
|
Object.entries(value as Record<string, unknown>).forEach(([k, v]) => {
|
|
const key = parentKey ? `${parentKey}[${k}]` : k;
|
|
toFormData(v, form, key);
|
|
});
|
|
return form;
|
|
}
|
|
|
|
if (parentKey) form.append(parentKey, String(value));
|
|
return form;
|
|
}
|
|
|
|
export function containsFile(obj: unknown): boolean {
|
|
if (!obj) return false;
|
|
if (obj instanceof File) return true;
|
|
if (Array.isArray(obj)) return obj.some(containsFile);
|
|
if (typeof obj === 'object') {
|
|
return Object.values(obj as Record<string, unknown>).some(containsFile);
|
|
}
|
|
return false;
|
|
}
|