The route helper functions are fairly well isolated from the rest of BaseService, with a few convenient entry points. They are easier to test in isolation. The way the code was written before, `pathToRegexp` was invoked once for every request, which seems inefficient. `route` was validated when it was used, though it seems more helpful to validate it up front. This breaks out `_makeFullUrl`, `_regex`, `_regexFromPath` into new helper functions `makeFullUrl`, `assertValidRoute`, `prepareRoute`, and `namedParamsForMatch`. It adds validation to route, and updates the services without patterns to include one, in order to pass the new validation rules.
64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
'use strict'
|
|
|
|
const makeBadge = require('../../gh-badges/lib/make-badge')
|
|
const analytics = require('../server/analytics')
|
|
const BaseService = require('./base')
|
|
const {
|
|
serverHasBeenUpSinceResourceCached,
|
|
setCacheHeadersForStaticResource,
|
|
} = require('./cache-headers')
|
|
const { makeSend } = require('./legacy-result-sender')
|
|
const coalesceBadge = require('./coalesce-badge')
|
|
const { prepareRoute, namedParamsForMatch } = require('./route')
|
|
|
|
module.exports = class BaseStaticService extends BaseService {
|
|
static register({ camp }, serviceConfig) {
|
|
const {
|
|
profiling: { makeBadge: shouldProfileMakeBadge },
|
|
} = serviceConfig
|
|
const { regex, captureNames } = prepareRoute(this.route)
|
|
|
|
camp.route(regex, async (queryParams, match, end, ask) => {
|
|
analytics.noteRequest(queryParams, match)
|
|
|
|
if (serverHasBeenUpSinceResourceCached(ask.req)) {
|
|
// Send Not Modified.
|
|
ask.res.statusCode = 304
|
|
ask.res.end()
|
|
return
|
|
}
|
|
|
|
const namedParams = namedParamsForMatch(captureNames, match, this)
|
|
const serviceData = await this.invoke(
|
|
{},
|
|
serviceConfig,
|
|
namedParams,
|
|
queryParams
|
|
)
|
|
|
|
const badgeData = coalesceBadge(
|
|
queryParams,
|
|
serviceData,
|
|
this.defaultBadgeData,
|
|
this
|
|
)
|
|
|
|
// The final capture group is the extension.
|
|
const format = match.slice(-1)[0]
|
|
badgeData.format = format
|
|
|
|
if (shouldProfileMakeBadge) {
|
|
console.time('makeBadge total')
|
|
}
|
|
const svg = makeBadge(badgeData)
|
|
if (shouldProfileMakeBadge) {
|
|
console.timeEnd('makeBadge total')
|
|
}
|
|
|
|
setCacheHeadersForStaticResource(ask.res)
|
|
|
|
makeSend(format, ask.res, end)(svg)
|
|
})
|
|
}
|
|
}
|