@bhavinkumarvegad/playwright-email-utils
Version:
Reusable utilities for handling emails in Playwright tests from Yopmail, Gmail and other providers.
66 lines (54 loc) • 2.07 kB
text/typescript
import { GmailMessage } from '../providers/gmail';
interface EmailParserConfig {
startMarker?: string;
endMarker?: string;
regex?: RegExp;
type: 'between-markers' | 'regex' | 'full-text';
}
export class EmailBodyParser {
/**
* Extract information from email body using different strategies
*/
static extractInfo(message: GmailMessage, config: EmailParserConfig): string | null {
if (!message.body) {
return null;
}
switch (config.type) {
case 'between-markers':
if (!config.startMarker || !config.endMarker) {
throw new Error('Start and end markers are required for between-markers type');
}
return this.extractBetweenMarkers(message.body, config.startMarker, config.endMarker);
case 'regex':
if (!config.regex) {
throw new Error('Regex pattern is required for regex type');
}
return this.extractWithRegex(message.body, config.regex);
case 'full-text':
return message.body;
default:
throw new Error(`Unsupported extraction type: ${config.type}`);
}
}
/**
* Extract text between two markers in the email body
*/
private static extractBetweenMarkers(text: string, startMarker: string, endMarker: string): string | null {
const startIndex = text.indexOf(startMarker);
if (startIndex === -1) return null;
const contentStartIndex = startIndex + startMarker.length;
const endIndex = text.indexOf(endMarker, contentStartIndex);
if (endIndex === -1) return null;
return text.substring(contentStartIndex, endIndex).trim();
}
/**
* Extract text using a regular expression
*/
private static extractWithRegex(text: string, pattern: RegExp): string | null {
const match = text.match(pattern);
if (!match) return null;
// If the regex has capture groups, return the first captured group
// Otherwise return the full match
return (match[1] || match[0]).trim();
}
}