Files
shields/services/dynamic/dynamic-xml.service.js
dependabot-preview[bot] 294aa1e1df Build(deps-dev): bump eslint-plugin-import from 2.17.3 to 2.18.0; autofixes (#3671)
* Build(deps-dev): bump eslint-plugin-import from 2.17.3 to 2.18.0

Bumps [eslint-plugin-import](https://github.com/benmosher/eslint-plugin-import) from 2.17.3 to 2.18.0.
- [Release notes](https://github.com/benmosher/eslint-plugin-import/releases)
- [Changelog](https://github.com/benmosher/eslint-plugin-import/blob/master/CHANGELOG.md)
- [Commits](https://github.com/benmosher/eslint-plugin-import/compare/v2.17.3...v2.18.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

* Autofixes
2019-07-08 12:13:46 -04:00

55 lines
1.5 KiB
JavaScript

'use strict'
const { DOMParser } = require('xmldom')
const xpath = require('xpath')
const { renderDynamicBadge, errorMessages } = require('../dynamic-common')
const { createRoute } = require('./dynamic-helpers')
const { BaseService, InvalidResponse } = require('..')
// This service extends BaseService because it uses a different XML parser
// than BaseXmlService which can be used with xpath.
//
// One way to create a more performant version would be to use the BaseXml
// JSON parser and write the queries in jsonpath instead. Then eventually
// deprecate the old version.
module.exports = class DynamicXml extends BaseService {
static get category() {
return 'dynamic'
}
static get route() {
return createRoute('xml')
}
static get defaultBadgeData() {
return {
label: 'custom badge',
}
}
async handle(namedParams, { url, query: pathExpression, prefix, suffix }) {
// 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)
const values = xpath
.select(pathExpression, parsed)
.map((node, i) => (pathIsAttr ? node.value : node.firstChild.data))
if (!values.length) {
throw new InvalidResponse({ prettyMessage: 'no result' })
}
return renderDynamicBadge({ value: values, prefix, suffix })
}
}