-
Notifications
You must be signed in to change notification settings - Fork 0
/
atomToGreenButtonJson.ts
95 lines (81 loc) · 2.75 KB
/
atomToGreenButtonJson.ts
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
import xml2js from 'xml2js'
import { updateGreenButtonContent } from './contentUpdaters.js'
import type { AtomJson, AtomJsonEntry } from './types/atomTypes.js'
import type {
GreenButtonEntry,
GreenButtonEntryContent,
GreenButtonJson
} from './types/entryTypes.js'
import {
atomLinksToGreenButtonLinks,
cleanContentJson,
getFirstXmlString
} from './utilities.js'
const parserOptions: xml2js.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: string
): Promise<GreenButtonJson> {
const atomJson = (await xml2js.parseStringPromise(
atomXml,
parserOptions
)) as AtomJson
let greenButtonFeed: GreenButtonJson
let atomJsonEntries: AtomJsonEntry[] = []
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: GreenButtonEntry = {
id: getFirstXmlString(item.id),
title: getFirstXmlString(item.title),
links: atomLinksToGreenButtonLinks(item.link ?? [], true),
publishedDate:
item.published === undefined
? undefined
: new Date(item.published as unknown as string),
updatedDate:
item.updated === undefined
? undefined
: new Date(item.updated as unknown as string),
content: content as unknown as GreenButtonEntryContent
}
updateGreenButtonContent(greenButtonEntry.content)
greenButtonFeed.entries.push(greenButtonEntry)
}
return greenButtonFeed
}