summaryrefslogtreecommitdiff
path: root/bin/wiki/ImportarDesdeURL/node_modules/metascraper/src/get-data.js
blob: 55627e61ec10d7032f9692ec8376c8b90221aed4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'use strict'

const { isString, map, fromPairs } = require('lodash')
const { hasValue } = require('@metascraper/helpers')
const mapValuesDeep = require('map-values-deep')

const xss = require('xss')

const noopTest = () => true

const getValue = async ({ htmlDom, url, rules, meta }) => {
  const lastIndex = rules.length
  let index = 0
  let value

  do {
    const rule = rules[index++]
    const test = rule.test || noopTest
    if (test({ htmlDom, url, meta })) {
      value = await rule({ htmlDom, url, meta })
    }
  } while (!hasValue(value) && index < lastIndex)

  return value
}

const escapeValue = (value, { escape }) =>
  !escape
    ? value
    : mapValuesDeep(value, value => (isString(value) ? xss(value) : value))

const getData = async ({ rules, htmlDom, url, escape }) => {
  const data = await Promise.all(
    map(rules, async ([propName, innerRules]) => {
      const rawValue = await getValue({ htmlDom, url, rules: innerRules })
      const value = hasValue(rawValue)
        ? escapeValue(rawValue, { escape })
        : null
      return [propName, value]
    })
  )

  return fromPairs(data)
}

module.exports = getData