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');
|
|
|
|
|
2023-03-06 08:33:32 -08:00
|
|
|
const binaryData = this.helpers.assertBinaryData(mediaPropertyName);
|
2023-02-22 23:51:08 -08:00
|
|
|
|
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
|
|
|
|
2023-03-06 08:33:32 -08:00
|
|
|
const fileName = mediaFileName || binaryData.fileName;
|
2023-02-22 23:51:08 -08:00
|
|
|
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();
|
2023-03-06 08:33:32 -08:00
|
|
|
formData.append('file', buffer, { contentType: binaryData.mimeType, filename: fileName });
|
2023-02-22 23:51:08 -08:00
|
|
|
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;
|
|
|
|
}
|