fix type errors in [DynamicXml] service (#4041)

* fix: type errors in DynamicXml service

* tests: add more tests for DynamicXml

* tests: another DynamicXml service test
This commit is contained in:
Caleb Cartwright
2019-10-08 15:48:43 -05:00
committed by GitHub
parent a66e4f9e10
commit 65f66642dd
3 changed files with 94 additions and 12 deletions

View File

@@ -27,18 +27,11 @@ module.exports = class DynamicXml extends BaseService {
}
}
async handle(namedParams, { url, query: pathExpression, prefix, suffix }) {
transform({ pathExpression, buffer }) {
// e.g. //book[2]/@id
const pathIsAttr = (
pathExpression.split('/').slice(-1)[0] || ''
).startsWith('@')
const { buffer } = await this._request({
url,
options: { headers: { Accept: 'application/xml, text/xml' } },
errorMessages,
})
const parsed = new DOMParser().parseFromString(buffer)
let values
@@ -47,14 +40,42 @@ module.exports = class DynamicXml extends BaseService {
} catch (e) {
throw new InvalidParameter({ prettyMessage: e.message })
}
values = values.map((node, i) =>
pathIsAttr ? node.value : node.firstChild.data
)
if (!Array.isArray(values)) {
throw new InvalidResponse({
prettyMessage: 'unsupported query',
})
}
values = values.reduce((accum, node) => {
if (pathIsAttr) {
accum.push(node.value)
} else if (node.firstChild) {
accum.push(node.firstChild.data)
}
return accum
}, [])
if (!values.length) {
throw new InvalidResponse({ prettyMessage: 'no result' })
}
return renderDynamicBadge({ value: values, prefix, suffix })
return { values }
}
async handle(_namedParams, { url, query: pathExpression, prefix, suffix }) {
const { buffer } = await this._request({
url,
options: { headers: { Accept: 'application/xml, text/xml' } },
errorMessages,
})
const { values: value } = this.transform({
pathExpression,
buffer,
})
return renderDynamicBadge({ value, prefix, suffix })
}
}