Files
shields/services/github/github-size.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

88 lines
2.2 KiB
JavaScript

import Joi from 'joi'
import prettyBytes from 'pretty-bytes'
import { nonNegativeInteger } from '../validators.js'
import { NotFound } from '../index.js'
import { GithubAuthV3Service } from './github-auth-service.js'
import { documentation, httpErrorsFor } from './github-helpers.js'
const queryParamSchema = Joi.object({
branch: Joi.string(),
}).required()
const schema = Joi.alternatives(
Joi.object({
size: nonNegativeInteger,
}).required(),
Joi.array().required()
)
export default class GithubSize extends GithubAuthV3Service {
static category = 'size'
static route = {
base: 'github/size',
pattern: ':user/:repo/:path+',
queryParamSchema,
}
static examples = [
{
title: 'GitHub file size in bytes',
namedParams: {
user: 'webcaetano',
repo: 'craft',
path: 'build/phaser-craft.min.js',
},
staticPreview: this.render({ size: 9170 }),
keywords: ['repo'],
documentation,
},
{
title: 'GitHub file size in bytes on a specified ref (branch/commit/tag)',
namedParams: {
user: 'webcaetano',
repo: 'craft',
path: 'build/phaser-craft.min.js',
},
staticPreview: this.render({ size: 9170 }),
keywords: ['repo'],
documentation,
queryParams: {
branch: 'master',
},
},
]
static render({ size }) {
return {
message: prettyBytes(size),
color: 'blue',
}
}
async fetch({ user, repo, path, branch }) {
if (branch) {
return this._requestJson({
url: `/repos/${user}/${repo}/contents/${path}?ref=${branch}`,
schema,
httpErrors: httpErrorsFor('repo, branch or file not found'),
})
} else {
return this._requestJson({
url: `/repos/${user}/${repo}/contents/${path}`,
schema,
httpErrors: httpErrorsFor('repo or file not found'),
})
}
}
async handle({ user, repo, path }, queryParams) {
const branch = queryParams.branch
const body = await this.fetch({ user, repo, path, branch })
if (Array.isArray(body)) {
throw new NotFound({ prettyMessage: 'not a regular file' })
}
return this.constructor.render({ size: body.size })
}
}