n8n-nodes-parse-pdf
Version:
Extract text, tables, and structured data from PDF files using PDF API Hub
108 lines • 5.66 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkApiResponse = checkApiResponse;
exports.normalizeUrl = normalizeUrl;
exports.prepareBinaryResponse = prepareBinaryResponse;
exports.createSingleFileMultipart = createSingleFileMultipart;
exports.createTwoFileMultipart = createTwoFileMultipart;
exports.parseJsonResponseBody = parseJsonResponseBody;
const n8n_workflow_1 = require("n8n-workflow");
function checkApiResponse(context, statusCode, responseBody, itemIndex) {
if (statusCode >= 200 && statusCode < 300)
return;
let apiMessage = `API request failed with status ${statusCode}`;
let bodyObj = {};
if (responseBody && typeof responseBody === 'object') {
bodyObj = responseBody;
if (typeof bodyObj.error === 'string')
apiMessage = bodyObj.error;
}
else if (typeof responseBody === 'string') {
try {
const parsed = JSON.parse(responseBody);
if (typeof parsed.error === 'string') {
apiMessage = parsed.error;
bodyObj = parsed;
}
}
catch { }
}
throw new n8n_workflow_1.NodeApiError(context.getNode(), bodyObj, { message: apiMessage, httpCode: String(statusCode), itemIndex });
}
function normalizeUrl(value) {
const trimmed = value.trim();
if (!trimmed)
return trimmed;
if (trimmed.startsWith('http://') || trimmed.startsWith('https://'))
return trimmed;
return `https://${trimmed}`;
}
async function prepareBinaryResponse(itemIndex, responseData, fallbackFileName, fallbackMimeType) {
var _a, _b, _c;
const headers = (_a = responseData.headers) !== null && _a !== void 0 ? _a : {};
const contentTypeHeader = (_b = (typeof headers['content-type'] === 'string' ? headers['content-type'] : undefined)) !== null && _b !== void 0 ? _b : (typeof headers['Content-Type'] === 'string' ? headers['Content-Type'] : undefined);
const contentType = ((_c = contentTypeHeader === null || contentTypeHeader === void 0 ? void 0 : contentTypeHeader.split(';')[0]) === null || _c === void 0 ? void 0 : _c.trim()) || fallbackMimeType;
let fileName = fallbackFileName;
if (!fileName)
fileName = 'output';
if (!fileName.includes('.') && contentType.includes('/')) {
const ext = contentType.includes('pdf') ? 'pdf' : contentType.includes('zip') ? 'zip' : 'bin';
fileName = `${fileName}.${ext}`;
}
const binaryData = await this.helpers.prepareBinaryData(Buffer.from(responseData.body), fileName, contentType);
return { json: { success: true }, binary: { data: binaryData }, pairedItem: { item: itemIndex } };
}
async function createSingleFileMultipart(itemIndex, binaryPropertyName, fields) {
var _a, _b;
const boundary = `----n8nFormBoundary${Math.random().toString(36).slice(2)}`;
const binaryData = this.helpers.assertBinaryData(itemIndex, binaryPropertyName);
const binaryDataBuffer = await this.helpers.getBinaryDataBuffer(itemIndex, binaryPropertyName);
const fileName = (_a = binaryData.fileName) !== null && _a !== void 0 ? _a : 'file.pdf';
const contentType = (_b = binaryData.mimeType) !== null && _b !== void 0 ? _b : 'application/pdf';
const parts = [];
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\nContent-Type: ${contentType}\r\n\r\n`));
parts.push(Buffer.from(binaryDataBuffer));
parts.push(Buffer.from('\r\n'));
for (const [key, value] of Object.entries(fields)) {
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${key}"\r\n\r\n${String(value)}\r\n`));
}
parts.push(Buffer.from(`--${boundary}--\r\n`));
return { body: Buffer.concat(parts), headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` } };
}
async function createTwoFileMultipart(itemIndex, file1BinaryProperty, file2BinaryProperty, method) {
const boundary = `----n8nFormBoundary${Math.random().toString(36).slice(2)}`;
const parts = [];
const appendFile = async (fieldName, binaryPropertyName) => {
var _a, _b;
const binaryData = this.helpers.assertBinaryData(itemIndex, binaryPropertyName);
const binaryDataBuffer = await this.helpers.getBinaryDataBuffer(itemIndex, binaryPropertyName);
const fileName = (_a = binaryData.fileName) !== null && _a !== void 0 ? _a : `${fieldName}.bin`;
const contentType = (_b = binaryData.mimeType) !== null && _b !== void 0 ? _b : 'application/octet-stream';
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${fieldName}"; filename="${fileName}"\r\nContent-Type: ${contentType}\r\n\r\n`));
parts.push(Buffer.from(binaryDataBuffer));
parts.push(Buffer.from('\r\n'));
};
await appendFile('file1', file1BinaryProperty);
await appendFile('file2', file2BinaryProperty);
if (method) {
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="method"\r\n\r\n${method}\r\n`));
}
parts.push(Buffer.from(`--${boundary}--\r\n`));
return { body: Buffer.concat(parts), headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` } };
}
function parseJsonResponseBody(body, itemIndex) {
let json;
if (typeof body === 'string') {
try {
json = JSON.parse(body);
}
catch {
json = { raw: body };
}
}
else {
json = (body !== null && body !== void 0 ? body : {});
}
return { json, pairedItem: { item: itemIndex } };
}
//# sourceMappingURL=helpers.js.map