Skip to content

Instantly share code, notes, and snippets.

@ecancino
Created February 26, 2025 05:35
Show Gist options
  • Select an option

  • Save ecancino/ec427fe40dafc304095286e1ffcb86d1 to your computer and use it in GitHub Desktop.

Select an option

Save ecancino/ec427fe40dafc304095286e1ffcb86d1 to your computer and use it in GitHub Desktop.
Object to FormData
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