phantom-marmiton/src/utils/browser.ts
2022-01-08 00:07:09 +01:00

68 lines
1.6 KiB
TypeScript

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 <T>(
func: (browser: puppeteer.Browser) => Promise<T>
): Promise<T> => {
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 <T>(
func: (page: puppeteer.Page) => Promise<T>
): Promise<T> => {
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 = <T, V extends keyof T>(
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("&");
};