Created
February 26, 2025 05:35
-
-
Save ecancino/ec427fe40dafc304095286e1ffcb86d1 to your computer and use it in GitHub Desktop.
Object to FormData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import "@total-typescript/ts-reset"; | |
| function isUndefined(value: unknown): value is undefined { | |
| return typeof value === "undefined"; | |
| } | |
| function isNull(value: unknown): value is null { | |
| return value === null; | |
| } | |
| function isNil(value: unknown): value is undefined | null { | |
| return isNull(value) || isUndefined(value); | |
| } | |
| function isDate(value: unknown): value is Date { | |
| return value instanceof Date; | |
| } | |
| function isBlob(value: unknown): value is Blob { | |
| return value instanceof Blob; | |
| } | |
| export type Primitives = | |
| | undefined | |
| | null | |
| | string | |
| | boolean | |
| | number | |
| | Date | |
| | Blob; | |
| export type SerializableObject = { | |
| [key: string]: Primitives | Array<Primitives>; | |
| }; | |
| export type Options = { | |
| dateFormatter: (date: Date) => string; | |
| }; | |
| const defaultOptions: Options = { | |
| dateFormatter: (date: Date) => date.toISOString(), | |
| }; | |
| function serializePrimitives( | |
| value: Omit<Primitives, "null" | "undefined">, | |
| options: Options | |
| ): Blob | string { | |
| if (isDate(value)) { | |
| return options.dateFormatter?.(value); | |
| } | |
| if (isBlob(value)) { | |
| return value; | |
| } | |
| return value.toString(); | |
| } | |
| export function serialize( | |
| object: SerializableObject, | |
| options: Options = defaultOptions | |
| ) { | |
| const formData = new FormData(); | |
| for (const [key, value] of Object.entries(object)) { | |
| ([] as Array<Primitives>) | |
| .concat(value) | |
| .filter((v) => !isNil(v)) | |
| .forEach((v) => { | |
| formData.append(key, serializePrimitives(v, options)); | |
| }); | |
| } | |
| return formData; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment