Skip to content

Instantly share code, notes, and snippets.

@worst-developer
Created July 10, 2017 13:23
Show Gist options
  • Save worst-developer/1e0710ef2e4ec2716634b44aa8419844 to your computer and use it in GitHub Desktop.
Save worst-developer/1e0710ef2e4ec2716634b44aa8419844 to your computer and use it in GitHub Desktop.
import Logger from "../Logger/Logger";
import * as FormData from "form-data";
class RequestNormalizer {
private policyTransformer: string = "json";
public convertToFormData(data) {
if (data.hasOwnProperty("attachment") === true) {
const formData = new FormData();
const file = data.file;
delete data.path;
const json = JSON.stringify(data);
formData.append(this.policyTransformer, json);
formData.append("attachment", file);
return formData;
}
return data;
}
public normalize(data: any): any {
const res = {};
Object.keys(data).forEach(key => {
const value = data[key];
// If value is NaN, send null instead.
if (Number.isNaN(value) === true) {
res[key] = null;
return;
}
// If value is undefined, don't send it to backend.
if (value === undefined) {
return;
}
res[key] = value;
});
Logger.debug(res, this.constructor.name);
return this.convertToFormData(res);
}
}
export default new RequestNormalizer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment