Files
n8n-enterprise-unlocked/packages/@n8n/imap/src/helpers/getMessage.ts
कारतोफ्फेलस्क्रिप्ट™ 9f87cc25a0 feat(Email Trigger (IMAP) Node): Migrate from imap-simple to @n8n/imap (#8899)
Co-authored-by: Jonathan Bennetts <jonathan.bennetts@gmail.com>
2024-04-09 11:33:10 +02:00

54 lines
1.4 KiB
TypeScript

import {
parseHeader,
type ImapMessage,
type ImapMessageBodyInfo,
type ImapMessageAttributes,
} from 'imap';
import type { Message, MessageBodyPart } from '../types';
/**
* Given an 'ImapMessage' from the node-imap library, retrieves the `Message`
*/
export async function getMessage(
/** an ImapMessage from the node-imap library */
message: ImapMessage,
): Promise<Message> {
return await new Promise((resolve) => {
let attributes: ImapMessageAttributes;
const parts: MessageBodyPart[] = [];
const messageOnBody = (stream: NodeJS.ReadableStream, info: ImapMessageBodyInfo) => {
let body: string = '';
const streamOnData = (chunk: Buffer) => {
body += chunk.toString('utf8');
};
stream.on('data', streamOnData);
stream.once('end', () => {
stream.removeListener('data', streamOnData);
parts.push({
which: info.which,
size: info.size,
body: /^HEADER/g.test(info.which) ? parseHeader(body) : body,
});
});
};
const messageOnAttributes = (attrs: ImapMessageAttributes) => {
attributes = attrs;
};
const messageOnEnd = () => {
message.removeListener('body', messageOnBody);
message.removeListener('attributes', messageOnAttributes);
resolve({ attributes, parts });
};
message.on('body', messageOnBody);
message.once('attributes', messageOnAttributes);
message.once('end', messageOnEnd);
});
}