Files
shields/services/github/github-commit-status.service.js
chris48s 14892e3943 Implement a pattern for dealing with upstream APIs which are slow on the first hit; affects [endpoint] (#9233)
* allow serviceData to override cacheSeconds with a longer value

* prevent [endpoint] json cacheSeconds property exceeding service default

* allow ShieldsRuntimeError to specify a cacheSeconds property

By default error responses use the cacheLength of
the service class throwing the error.

This allows error to tell the handling layer the maxAge
that should be set on the error badge response.

* add customExceptions param

This

1. allows us to specify custom properties to pass to the exception
   constructor if we throw any of the standard got errors
   e.g: `ETIMEDOUT`, `ECONNRESET`, etc
2. uses a custom `cacheSeconds` property (if set on the exception)
   to set the response maxAge

* customExceptions --> systemErrors

* errorMessages --> httpErrors
2023-06-13 21:08:43 +01:00

75 lines
2.0 KiB
JavaScript

import Joi from 'joi'
import { NotFound, InvalidParameter } from '../index.js'
import { GithubAuthV3Service } from './github-auth-service.js'
import { documentation, httpErrorsFor } from './github-helpers.js'
const schema = Joi.object({
// https://stackoverflow.com/a/23969867/893113
status: Joi.equal('identical', 'ahead', 'behind', 'diverged'),
}).required()
export default class GithubCommitStatus extends GithubAuthV3Service {
static category = 'issue-tracking'
static route = {
base: 'github/commit-status',
pattern: ':user/:repo/:branch/:commit',
}
static examples = [
{
title: 'GitHub commit merge status',
namedParams: {
user: 'badges',
repo: 'shields',
branch: 'master',
commit: '5d4ab86b1b5ddfb3c4a70a70bd19932c52603b8c',
},
staticPreview: this.render({
isInBranch: true,
branch: 'master',
}),
keywords: ['branch'],
documentation,
},
]
static defaultBadgeData = { label: 'commit status' }
static render({ isInBranch, branch }) {
if (isInBranch) {
return {
message: `in ${branch}`,
color: 'brightgreen',
}
} else {
// status: ahead or diverged
return {
message: `not in ${branch}`,
color: 'yellow',
}
}
}
async handle({ user, repo, branch, commit }) {
let status
try {
;({ status } = await this._requestJson({
url: `/repos/${user}/${repo}/compare/${branch}...${commit}`,
httpErrors: httpErrorsFor('commit or branch not found'),
schema,
}))
} catch (e) {
if (e instanceof NotFound) {
const { message } = this._parseJson(e.buffer)
if (message && message.startsWith('No common ancestor between')) {
throw new InvalidParameter({ prettyMessage: 'no common ancestor' })
}
}
throw e
}
const isInBranch = status === 'identical' || status === 'behind'
return this.constructor.render({ isInBranch, branch })
}
}