Files
shields/services/cdnjs/cdnjs.service.js
chris48s ae190c5f07 generate static examples without api call [apm appveyor cdnjs clojars gem npm uptimerobot] (#1740)
* allow service classes to define a static example
* define static example for some services
  (apm, appveyor, cdnjs, clojars, gem, librariesio, npm, uptimerobot)
* add/update tests


This allows us to show an example without making an API call to a live service for better performance.

We can now specify 3 fields in the example definition:

* urlPattern for the version with placeholders e.g: /npm/dw/:package.svg
* ExampleUrl/Uri for the concrete example e.g: /npm/dw/localeval.svg
* PreviewUrl/Uri for the static (or live) image we will actually show
2018-08-23 20:22:24 +01:00

70 lines
1.5 KiB
JavaScript

'use strict'
const Joi = require('joi')
const BaseJsonService = require('../base-json')
const { NotFound } = require('../errors')
const { addv: versionText } = require('../../lib/text-formatters')
const { version: versionColor } = require('../../lib/color-formatters')
const cdnjsSchema = Joi.object({
// optional due to non-standard 'not found' condition
version: Joi.string(),
}).required()
module.exports = class Cdnjs extends BaseJsonService {
async fetch({ library }) {
const url = `https://api.cdnjs.com/libraries/${library}?fields=version`
return this._requestJson({
url,
schema: cdnjsSchema,
})
}
static render({ version }) {
return {
message: versionText(version),
color: versionColor(version),
}
}
async handle({ library }) {
const json = await this.fetch({ library })
if (Object.keys(json).length === 0) {
/* Note the 'not found' response from cdnjs is:
status code = 200, body = {} */
throw new NotFound()
}
return this.constructor.render({ version: json.version })
}
// Metadata
static get defaultBadgeData() {
return { label: 'cdnjs' }
}
static get category() {
return 'version'
}
static get url() {
return {
base: 'cdnjs/v',
format: '(.+)',
capture: ['library'],
}
}
static get examples() {
return [
{
urlPattern: ':library',
exampleUrl: 'jquery',
staticExample: this.render({ version: '1.5.2' }),
keywords: ['cdn', 'cdnjs'],
},
]
}
}