-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLibraryParser.js
96 lines (78 loc) · 2.76 KB
/
LibraryParser.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const xmlparser = require("fast-xml-parser");
const fs = require("fs");
class LibraryParser {
constructor(filePath) {
const options = {
ignoreAttributes: false,
allowBooleanAttributes: true,
processEntities: false
};
this.parser = new xmlparser.XMLParser(options);
const builderOptions = {
ignoreAttributes : false,
format: true,
processEntities: false
};
this.builder = new xmlparser.XMLBuilder(builderOptions);
let xml = fs.readFileSync(filePath);
this.xmlData = this.parser.parse(xml);
this.outputXml = { ...this.xmlData };
}
getPageNode (pageId) {
return this.getNode(pageId)
}
getNode (contentId) {
return this.xmlData.library.content.find(content => content['@_content-id'] === contentId);
}
removeNode (contentId) {
const index = this.outputXml.library.content.findIndex(content => content['@_content-id'] === contentId);
if (index > -1) {
this.outputXml.library.content.splice(index, 1);
}
}
getPageNodes(pageId) {
const pageNode = this.getPageNode(pageId);
const relatedNodes = this.getContentLinksNodes(pageNode);
return [pageNode, ...relatedNodes];
}
getContentLinksNodes(node) {
let nodes = [];
let contentLinks = node['content-links'] && node['content-links']['content-link'] ? node['content-links']['content-link'] : [];
contentLinks = Array.isArray(contentLinks) ? contentLinks : [contentLinks]
if (contentLinks.length) {
for (const contentLink of contentLinks) {
const contentId = contentLink['@_content-id'];
const contentNode = this.getNode(contentId);
nodes.push(contentNode);
nodes = nodes.concat(this.getContentLinksNodes(contentNode));
}
}
return nodes;
}
getXmlWithNodes(nodes) {
var newData = { ...this.xmlData };
newData.library = {
content: nodes,
'@_xmlns': newData.library['@_xmlns'],
'@_library-id': newData.library['@_library-id']
};
return this.builder.build(newData);
}
getXmlWithoutPage(pageId) {
const pageNodes = this.getPageNodes(pageId);
for (const pageNode of pageNodes) {
this.removeNode(pageNode['@_content-id']);
}
return this.getOutputXml();
}
getAllNodes() {
return this.xmlData.library.content;
}
addNodes(nodes) {
this.xmlData.library.content = this.xmlData.library.content.concat(nodes);
}
getOutputXml() {
return this.builder.build(this.outputXml);
}
}
module.exports = LibraryParser;