UNPKG

2.23 kBJavaScriptView Raw
1const url = require('url')
2const fetch = require('node-fetch')
3const { safeJoin } = require('safe-join')
4
5// supported repo host types
6const GITHUB = Symbol('GITHUB')
7// const BITBUCKET = Symbol('BITBUCKET')
8// const GITLAB = Symbol('GITLAB')
9
10/**
11 * Takes a url like https://github.com/netlify-labs/all-the-functions/tree/master/functions/9-using-middleware
12 * and returns https://api.github.com/repos/netlify-labs/all-the-functions/contents/functions/9-using-middleware
13 */
14async function readRepoURL(_url) {
15 // TODO: use `url.URL()` instead
16 // eslint-disable-next-line node/no-deprecated-api
17 const URL = url.parse(_url)
18 const repoHost = validateRepoURL(_url)
19 if (repoHost !== GITHUB) throw new Error('only github repos are supported for now')
20 const [owner_and_repo, contents_path] = parseRepoURL(repoHost, URL)
21 const folderContents = await getRepoURLContents(repoHost, owner_and_repo, contents_path)
22 return folderContents
23}
24
25async function getRepoURLContents(repoHost, owner_and_repo, contents_path) {
26 // naive joining strategy for now
27 if (repoHost === GITHUB) {
28 // https://developer.github.com/v3/repos/contents/#get-contents
29 const APIURL = safeJoin('https://api.github.com/repos', owner_and_repo, 'contents', contents_path)
30 return fetch(APIURL)
31 .then(x => x.json())
32 .catch(
33 error => console.error('Error occurred while fetching ', APIURL, error) // eslint-disable-line no-console
34 )
35 }
36 throw new Error('unsupported host ', repoHost)
37}
38
39function validateRepoURL(_url) {
40 // TODO: use `url.URL()` instead
41 // eslint-disable-next-line node/no-deprecated-api
42 const URL = url.parse(_url)
43 if (URL.host !== 'github.com') return null
44 // other validation logic here
45 return GITHUB
46}
47function parseRepoURL(repoHost, URL) {
48 // naive splitting strategy for now
49 if (repoHost === GITHUB) {
50 // https://developer.github.com/v3/repos/contents/#get-contents
51 const [owner_and_repo, contents_path] = URL.path.split('/tree/master') // what if it's not master? note that our contents retrieval may assume it is master
52 return [owner_and_repo, contents_path]
53 }
54 throw new Error('unsupported host ', repoHost)
55}
56
57module.exports = {
58 readRepoURL,
59 validateRepoURL
60}