smartrequest/ts/smartrequest.formdata.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2018-08-13 23:47:54 +00:00
import * as plugins from './smartrequest.plugins';
import * as interfaces from './smartrequest.interfaces';
import { request } from './smartrequest.request';
2018-07-19 14:16:02 +00:00
/**
* the interfae for FormFieldData
*/
export interface IFormField {
name: string;
2018-08-13 23:47:54 +00:00
type: 'string' | 'filePath' | 'Buffer';
2018-07-19 14:16:02 +00:00
payload: string;
}
2018-08-13 23:47:54 +00:00
const appendFormField = async (formDataArg: plugins.formData, formDataField: IFormField) => {
if (formDataField.type === 'filePath') {
let fileData = plugins.fs.readFileSync(plugins.path.join(process.cwd(), formDataField.payload));
formDataArg.append('file', fileData, {
2018-07-19 22:01:41 +00:00
filename: 'upload.pdf',
contentType: 'application/pdf'
});
2018-07-19 14:16:02 +00:00
}
};
export const postFormData = async (
urlArg: string,
optionsArg: interfaces.ISmartRequestOptions = {},
payloadArg: IFormField[]
) => {
const form = new plugins.formData();
for (const formField of payloadArg) {
await appendFormField(form, formField);
}
const requestOptions = Object.assign({}, optionsArg, {
2018-07-19 23:06:25 +00:00
method: 'POST',
headers: {
2018-08-13 23:47:54 +00:00
...optionsArg.headers,
2018-07-19 22:35:23 +00:00
...form.getHeaders()
},
requestBody: form
});
2018-07-19 14:16:02 +00:00
// lets fire the actual request for sending the formdata
2018-07-19 21:32:43 +00:00
const response = await request(urlArg, requestOptions);
return response;
2018-07-19 14:16:02 +00:00
};