Files
shields/services/dynamic/dynamic-xml.service.js
Paul Melnikow 2d7be31b0c Validate query params in BaseService (#3042)
This is a mid-sized PR that adds query param validation to BaseService and updates most of the services which use query param validation to use it. There are a couple minor tweaks I made along the way.

Fix #2676
2019-02-20 22:24:47 -05:00

52 lines
1.4 KiB
JavaScript

'use strict'
const { DOMParser } = require('xmldom')
const xpath = require('xpath')
const { BaseService, InvalidResponse } = require('..')
const { renderDynamicBadge, errorMessages } = require('../dynamic-common')
const { createRoute } = require('./dynamic-helpers')
// 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 }) {
const pathIsAttr = pathExpression.includes('@')
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 })
}
}