2023-01-27 03:22:44 -08:00
|
|
|
import type { IDataObject, IExecuteSingleFunctions, IHttpRequestOptions } from 'n8n-workflow';
|
|
|
|
import { NodeOperationError } from 'n8n-workflow';
|
2022-09-29 17:17:46 -07:00
|
|
|
|
|
|
|
import FormData from 'form-data';
|
|
|
|
|
2023-02-22 23:51:08 -08:00
|
|
|
export async function getUploadFormData(
|
2022-09-29 17:17:46 -07:00
|
|
|
this: IExecuteSingleFunctions,
|
2023-02-22 23:51:08 -08:00
|
|
|
): Promise<{ fileName: string; formData: FormData }> {
|
|
|
|
const mediaPropertyName = ((this.getNodeParameter('mediaPropertyName') as string) || '').trim();
|
|
|
|
if (!mediaPropertyName)
|
|
|
|
throw new NodeOperationError(this.getNode(), 'Parameter "mediaPropertyName" is not defined');
|
|
|
|
|
|
|
|
const { binary: binaryData } = this.getInputData();
|
|
|
|
if (!binaryData) throw new NodeOperationError(this.getNode(), 'Binary data missing in input');
|
|
|
|
|
|
|
|
const binaryFile = binaryData[mediaPropertyName];
|
|
|
|
if (binaryFile === undefined)
|
|
|
|
throw new NodeOperationError(this.getNode(), 'Could not find file in node input data');
|
|
|
|
|
2022-09-29 17:17:46 -07:00
|
|
|
const mediaFileName = (this.getNodeParameter('additionalFields') as IDataObject).mediaFileName as
|
|
|
|
| string
|
|
|
|
| undefined;
|
2023-02-22 23:51:08 -08:00
|
|
|
|
|
|
|
const fileName = mediaFileName || binaryFile.fileName;
|
|
|
|
if (!fileName)
|
2022-09-29 17:17:46 -07:00
|
|
|
throw new NodeOperationError(this.getNode(), 'No file name given for media upload.');
|
|
|
|
|
|
|
|
const buffer = await this.helpers.getBinaryDataBuffer(mediaPropertyName);
|
|
|
|
|
2023-02-22 23:51:08 -08:00
|
|
|
const formData = new FormData();
|
|
|
|
formData.append('file', buffer, { contentType: binaryFile.mimeType, filename: fileName });
|
|
|
|
formData.append('messaging_product', 'whatsapp');
|
2022-09-29 17:17:46 -07:00
|
|
|
|
2023-02-22 23:51:08 -08:00
|
|
|
return { fileName, formData };
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function setupUpload(
|
|
|
|
this: IExecuteSingleFunctions,
|
|
|
|
requestOptions: IHttpRequestOptions,
|
|
|
|
) {
|
|
|
|
const uploadData = await getUploadFormData.call(this);
|
|
|
|
requestOptions.body = uploadData.formData;
|
2022-09-29 17:17:46 -07:00
|
|
|
return requestOptions;
|
|
|
|
}
|