-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (48 loc) · 1.34 KB
/
index.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
const cheerio = require('cheerio');
class Mapper {
constructor(html, selector) {
this.$ = cheerio.load(html);
this.selector = selector;
}
parse(sel, $context) {
const { attr, data, innerHTML, outerHTML, parse } = sel;
let result = attr
? $context.attr(attr)
: data
? $context.data(data)
: innerHTML
? this.$($context).html()
: outerHTML
? this.$.html($context)
: $context.text();
if (result && parse) {
result = parse(result);
}
return result;
}
extractSelect(sel, $context = null) {
const { path, multiple, nodes } = sel;
const $children = this.$(path, $context);
if (nodes) {
const reduceCallback = i => (acc, n) => {
acc[n.key] = this.extractSelect(n, $children.eq(i));
return acc;
};
return multiple
? $children.map(i => nodes.reduce(reduceCallback(i), {})).get()
: nodes.reduce(reduceCallback(0), {});
}
return multiple
? $children.map(i => this.parse(sel, $children.eq(i))).get()
: this.parse(sel, $children.eq(0));
}
extract() {
return this.selector instanceof Array
? this.selector.reduce(
(acc, s) => Object.assign(acc, { [s.key]: this.extractSelect(s) }),
{}
)
: this.extractSelect(this.selector);
}
}
module.exports = Mapper;