import puppeteer from "puppeteer"; /** * open a browser with puppeteer and call the parameter function within it * the browser will be closed after func execution * @param func function to execute after opening the browser and before closing it * @returns */ export const withBrowserOpened = async ( func: (browser: puppeteer.Browser) => Promise ): Promise => { const browser = await puppeteer.launch({ args: ["--no-sandbox"], }); const res = await func(browser); await browser.close(); return res; }; /** * open a page with puppeteer and call the parameter function within it * the page will be closed after func execution * @param func function to execute after opening a page and before closing it * @returns */ export const withPageOpened = async ( func: (page: puppeteer.Page) => Promise ): Promise => { return await withBrowserOpened(async (browser) => { const page = await browser.newPage(); const res = await func(page); await page.close(); return res; }); }; /** * transform object to url parameters * array will write multiple time the same argument name * @param opts object to transform * @param whitelist key to write from object * @returns */ export const optionsToUrlParams = ( opts: T, whitelist: V[] ): string => { return whitelist .map((key) => { if (!opts[key]) return ""; const value = opts[key]; if (Array.isArray(value)) { return value.map((val) => `${key}=${val}`).join("&"); } else { return `${key}=${value}`; } }) .filter(Boolean) .join("&"); };