front-hub/src/utils/jsonToFormdata.ts

46 lines
1015 B
TypeScript
Raw Normal View History

2023-11-05 23:33:40 +00:00
import type { Attachment } from "@root/model/attachment"
2024-08-28 22:24:38 +00:00
import { transliterate } from 'transliteration';
2023-07-06 21:52:07 +00:00
type KeyValue<T = string> = {
[key: string]: T;
};
const convertBinaryStringToFile = ({
2023-11-05 23:33:40 +00:00
name,
content,
mimetype,
2023-07-06 21:52:07 +00:00
}: Attachment): File => {
2023-11-05 23:33:40 +00:00
const bytes = new Uint8Array(content.length)
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
for (let index = 0; index < content.length; index += 1) {
bytes[index] = content.charCodeAt(index)
}
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
const blob = new Blob([bytes], { type: mimetype })
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
return new File([blob], name, { type: blob.type })
}
2023-07-06 21:52:07 +00:00
export const jsonToFormdata = (
2023-11-05 23:33:40 +00:00
json: KeyValue<string | Attachment>
2023-07-06 21:52:07 +00:00
): FormData => {
2023-11-05 23:33:40 +00:00
const formData = new FormData()
2024-08-28 22:24:38 +00:00
if (json.egrule !== undefined) delete json.egrule
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
for (const key in json) {
if (!key) continue
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
const value = json[key]
2024-08-28 22:24:38 +00:00
if (typeof value !== "string") value.name = transliterate(value.name.replace(/\s/g, '_'))
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
if (typeof value !== "string") {
formData.append(key, convertBinaryStringToFile(value))
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
continue
}
2023-07-06 21:52:07 +00:00
2023-11-05 23:33:40 +00:00
formData.append(key, value)
}
return formData
}