pass matching mime type to xmldom; test [dynamicxml] (#10830)
* feat: pass matching mime type to xmldom If the `Content-Type` header contains one of the mime types supported by `DOMParser`, the first matching mime type will be used instead of `text/xml`. The default is still `text/xml` for cases when the header is not present or none of the mime types from the list are present. * factor out and add tests --------- Co-authored-by: chris48s <git@chris-shaw.dev>
This commit is contained in:
committed by
GitHub
parent
152b8e9a64
commit
007a7e6c47
@@ -1,4 +1,4 @@
|
||||
import { DOMParser } from '@xmldom/xmldom'
|
||||
import { DOMParser, MIME_TYPE } from '@xmldom/xmldom'
|
||||
import xpath from 'xpath'
|
||||
import { MetricNames } from '../../core/base-service/metric-helper.js'
|
||||
import { renderDynamicBadge, httpErrors } from '../dynamic-common.js'
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
} from '../index.js'
|
||||
import { createRoute } from './dynamic-helpers.js'
|
||||
|
||||
const MIME_TYPES = Object.values(MIME_TYPE)
|
||||
|
||||
const description = `
|
||||
The Dynamic XML Badge allows you to extract an arbitrary value from any
|
||||
XML Document using an XPath selector and show it on a badge.
|
||||
@@ -70,6 +72,10 @@ export default class DynamicXml extends BaseService {
|
||||
|
||||
static defaultBadgeData = { label: 'custom badge' }
|
||||
|
||||
getmimeType(contentType) {
|
||||
return MIME_TYPES.find(mime => contentType.includes(mime)) ?? 'text/xml'
|
||||
}
|
||||
|
||||
transform({ pathExpression, buffer, contentType = 'text/xml' }) {
|
||||
// e.g. //book[2]/@id
|
||||
const pathIsAttr = (
|
||||
@@ -136,11 +142,8 @@ export default class DynamicXml extends BaseService {
|
||||
})
|
||||
|
||||
let contentType = 'text/xml'
|
||||
if (
|
||||
res.headers['content-type'] &&
|
||||
res.headers['content-type'].includes('text/html')
|
||||
) {
|
||||
contentType = 'text/html'
|
||||
if (res.headers['content-type']) {
|
||||
contentType = this.getmimeType(res.headers['content-type'])
|
||||
}
|
||||
|
||||
const { values: value } = this.transform({
|
||||
|
||||
@@ -157,4 +157,19 @@ describe('DynamicXml', function () {
|
||||
values: ['Herman Melville - Moby-Dick'],
|
||||
})
|
||||
})
|
||||
|
||||
test(DynamicXml.prototype.getmimeType, () => {
|
||||
// known types
|
||||
given('text/html').expect('text/html')
|
||||
given('application/xml').expect('application/xml')
|
||||
given('application/xhtml+xml').expect('application/xhtml+xml')
|
||||
given('image/svg+xml').expect('image/svg+xml')
|
||||
|
||||
// with character set
|
||||
given('text/html; charset=utf-8').expect('text/html')
|
||||
|
||||
// should fall back to text/xml if mime type is not one of the known types
|
||||
given('text/csv').expect('text/xml')
|
||||
given('foobar').expect('text/xml')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user