Files
shields/services/dynamic/dynamic-json.service.js
Paul Melnikow 6a737b7b38 Rewrite the DynamicJson badge (#2399)
This starts the rewrite of the dynamic badges. I've pulled into BaseService an initial version of the query param validation from #2325.

I've extended from BaseJsonService to avoid duplicating the deserialization logic, though it means there is a bit of duplicated code among the three dynamic services. The way to unravel this would be to move the logic from `_requestJson` and friends from the base classes into functions so DynamicJson can inherit from BaseDynamic. Would that be worth it?

This introduces a regression of #1446 for this badge.

Close #2345
2018-12-06 16:45:40 -05:00

52 lines
1.0 KiB
JavaScript

'use strict'
const Joi = require('joi')
const jp = require('jsonpath')
const BaseJsonService = require('../base-json')
const { InvalidResponse } = require('../errors')
const {
createRoute,
queryParamSchema,
errorMessages,
renderDynamicBadge,
} = require('./dynamic-helpers')
module.exports = class DynamicJson extends BaseJsonService {
static get category() {
return 'dynamic'
}
static get route() {
return createRoute('json')
}
static get defaultBadgeData() {
return {
label: 'custom badge',
}
}
async handle(namedParams, queryParams) {
const {
url,
query: pathExpression,
prefix,
suffix,
} = this.constructor._validateQueryParams(queryParams, queryParamSchema)
const data = await this._requestJson({
schema: Joi.any(),
url,
errorMessages,
})
const values = jp.query(data, pathExpression)
if (!values.length) {
throw new InvalidResponse({ prettyMessage: 'no result' })
}
return renderDynamicBadge({ values, prefix, suffix })
}
}