(options: LinksBuilderOptions)
| 17 | const isPartialUrlRegExp = /^(?!https?:).*/i; |
| 18 | |
| 19 | export function getProductLinksBuilder(options: LinksBuilderOptions) { |
| 20 | return (docElement: cheerio.Cheerio, series: Series): Link[] => { |
| 21 | const productElements = docElement.find(options.productsSelector); |
| 22 | const links: Link[] = []; |
| 23 | for (let i = 0; i < productElements.length; i++) { |
| 24 | const productElement = productElements.eq(i); |
| 25 | const titleElement = productElement.find(options.titleSelector).first(); |
| 26 | |
| 27 | const title = options.titleAttribute |
| 28 | ? titleElement.attr()?.[options.titleAttribute] |
| 29 | : titleElement.text()?.replace(/\n/g, ' ').trim(); |
| 30 | |
| 31 | if (!title) { |
| 32 | continue; |
| 33 | } |
| 34 | |
| 35 | let urlElement = titleElement; |
| 36 | |
| 37 | if (options.urlSelector) { |
| 38 | urlElement = urlElement.find(options.urlSelector).first(); |
| 39 | } |
| 40 | |
| 41 | let url = urlElement.attr()?.href; |
| 42 | |
| 43 | if (!url) { |
| 44 | continue; |
| 45 | } |
| 46 | |
| 47 | if (isPartialUrlRegExp.exec(url)) { |
| 48 | url = options.sitePrefix + url; |
| 49 | } |
| 50 | |
| 51 | const card = parseCard(title); |
| 52 | |
| 53 | if (card) { |
| 54 | links.push({ |
| 55 | brand: card.brand as any, |
| 56 | model: card.model, |
| 57 | series, |
| 58 | url, |
| 59 | }); |
| 60 | } else { |
| 61 | logger.error(`Failed to parse card: ${title}`, {url}); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | return links; |
| 66 | }; |
| 67 | } |
| 68 | |
| 69 | export function parseCard(name: string): Card | null { |
| 70 | name = name.replace(/\w+-\w+-[^ ]+/g, ''); |
no test coverage detected