Skip to content

Instantly share code, notes, and snippets.

@afranioce
Created June 5, 2019 17:44
Show Gist options
  • Save afranioce/6d8b9da77fd5f101242383693c532c82 to your computer and use it in GitHub Desktop.
Save afranioce/6d8b9da77fd5f101242383693c532c82 to your computer and use it in GitHub Desktop.
Format deep object to formData
class FormDataBuilder {
static BuildObject2FormData<T>(obj: T): FormData {
const formData: FormData = new FormData();
if (obj == null) {
return formData;
}
this.PopulateFormData(formData, '', obj);
return formData;
}
private static PopulateArray<T>(params: FormData, prefix: string, val: Array<T>): void {
val.forEach((prop, index) => {
const key = prefix + '[' + index + ']';
const value: any = val[index];
this.PopulateFormData(params, key, value);
});
}
private static PopulateObject<T>(params: FormData, prefix: string, val: T) {
const objectKeys = Object.keys(val) as Array<keyof T>;
if (prefix) {
prefix = prefix + '.';
}
for (let prop of objectKeys) {
const key = prefix + prop;
const value = val[prop];
this.PopulateFormData(params, key, value);
};
}
private static PopulateFormData(params: FormData, key: string, value: any): void {
if (this.isArray(value)) {
this.PopulateArray(params, key, value);
}
else if (this.isDate(value)) {
params.append(key, value.toISOString());
}
else if (this.isObject(value) && !this.isBlob(value) && !this.isFile(value)) {
this.PopulateObject(params, key, value);
}
else {
params.append(key, this.isNull(value) ? '' : value);
}
}
private static isNull(value) {
return value === null;
}
private static isArray(value) {
return value instanceof Array;
}
private static isObject(value) {
return value instanceof Object;
}
private static isDate(value) {
return value instanceof Date;
}
private static isBlob(value) {
return value &&
typeof value.size === 'number' &&
typeof value.type === 'string' &&
typeof value.slice === 'function';
}
private static isFile(value) {
return this.isBlob(value) &&
(typeof value.lastModifiedDate === 'object'
|| typeof value.lastModified === 'number')
&& typeof value.name === 'string';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment