Files
shields/services/github/github-common-fetch.js
Paul Melnikow 226fa67a02 Create shortcut for BaseService-related imports (#2809)
Continue to implement #2698:

- Add `core/base-service/index.js` (but hold off on moving the things it imports)
- Add shortcuts in `services/index.js` for Base*Service, errors, and deprecatedService. This file will be streamlined later to avoid cluttering it with rarely used bits.
- Apply consistent ordering of imports and use of `module.exports` in testers.
- Remove some renaming of imports.
- Remove obsolete tests here and there.
2019-01-21 15:41:24 -05:00

62 lines
1.6 KiB
JavaScript

'use strict'
const Joi = require('joi')
const { InvalidResponse } = require('..')
const { errorMessagesFor } = require('./github-helpers')
const issueSchema = Joi.object({
head: Joi.object({
sha: Joi.string().required(),
}).required(),
}).required()
async function fetchIssue(serviceInstance, { user, repo, number }) {
return serviceInstance._requestJson({
schema: issueSchema,
url: `/repos/${user}/${repo}/pulls/${number}`,
errorMessages: errorMessagesFor('pull request or repo not found'),
})
}
const contentSchema = Joi.object({
// https://github.com/hapijs/joi/issues/1430
content: Joi.string().required(),
encoding: Joi.equal('base64').required(),
}).required()
async function fetchJsonFromRepo(
serviceInstance,
{ schema, user, repo, branch = 'master', filename }
) {
let url, options
if (serviceInstance.staticAuthConfigured) {
url = `/repos/${user}/${repo}/contents/${filename}`
options = { qs: { ref: branch } }
} else {
url = `https://raw.githubusercontent.com/${user}/${repo}/${branch}/${filename}`
}
const { content } = await serviceInstance._requestJson({
schema: contentSchema,
url,
options,
errorMessages: errorMessagesFor(
`repo not found, branch not found, or ${filename} missing`
),
})
let decoded
try {
decoded = Buffer.from(content, 'base64').toString('utf-8')
} catch (e) {
throw InvalidResponse({ prettyMessage: 'undecodable content' })
}
const json = serviceInstance._parseJson(decoded)
return serviceInstance.constructor._validate(json, schema)
}
module.exports = {
fetchIssue,
fetchJsonFromRepo,
}