-
Notifications
You must be signed in to change notification settings - Fork 0
/
atomToGreenButtonJson.js
64 lines (64 loc) · 2.57 KB
/
atomToGreenButtonJson.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
import xml2js from 'xml2js';
import { updateGreenButtonContent } from './contentUpdaters.js';
import { atomLinksToGreenButtonLinks, cleanContentJson, getFirstXmlString } from './utilities.js';
const parserOptions = {
tagNameProcessors: [xml2js.processors.stripPrefix]
};
/**
* Parses a string of Green Button XML into a JavaScript object.
* @param {string} atomXml A string of valid Green Button XML.
* @returns {GreenButtonJson} Green Button object
*/
export async function atomToGreenButtonJson(atomXml) {
const atomJson = (await xml2js.parseStringPromise(atomXml, parserOptions));
let greenButtonFeed;
let atomJsonEntries = [];
if (atomJson.entry !== undefined) {
greenButtonFeed = {
id: getFirstXmlString(atomJson.entry.id),
title: getFirstXmlString(atomJson.entry.title),
links: atomLinksToGreenButtonLinks(atomJson.entry.link ?? [], false),
updatedDate: atomJson.entry.updated !== undefined &&
atomJson.entry.updated.length > 0
? new Date(atomJson.entry.updated[0])
: undefined,
entries: []
};
atomJsonEntries = [atomJson.entry];
// eslint-disable-next-line unicorn/no-negated-condition
}
else if (atomJson.feed !== undefined) {
greenButtonFeed = {
id: getFirstXmlString(atomJson.feed.id),
title: getFirstXmlString(atomJson.feed.title),
links: atomLinksToGreenButtonLinks(atomJson.feed.link ?? [], false),
updatedDate: atomJson.feed.updated !== undefined && atomJson.feed.updated.length > 0
? new Date(atomJson.feed.updated[0])
: undefined,
entries: []
};
atomJsonEntries = atomJson.feed.entry ?? [];
}
else {
throw new Error('Invalid Green Button XML');
}
for (const item of atomJsonEntries) {
const content = item.content[0];
cleanContentJson(content);
const greenButtonEntry = {
id: getFirstXmlString(item.id),
title: getFirstXmlString(item.title),
links: atomLinksToGreenButtonLinks(item.link ?? [], true),
publishedDate: item.published === undefined
? undefined
: new Date(item.published),
updatedDate: item.updated === undefined
? undefined
: new Date(item.updated),
content: content
};
updateGreenButtonContent(greenButtonEntry.content);
greenButtonFeed.entries.push(greenButtonEntry);
}
return greenButtonFeed;
}