Skip to content

Commit

Permalink
feat: add github branches api
Browse files Browse the repository at this point in the history
  • Loading branch information
Rob Ellison committed Aug 26, 2023
1 parent 1636ffb commit 1e13914
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
87 changes: 87 additions & 0 deletions lib/github/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,90 @@ function createFilterRegex(filter) {
const escapedFilter = filter.replace(/\./g, "\\.").replace(/\*/g, ".*");
return new RegExp(`^.*${escapedFilter}$`, "i");
}





const linkParser = (linkHeader) => {
const re = /<.*(?=>; rel=\"next\")/g;
let arrRes = [];
while ((arrRes = re.exec(linkHeader)) !== null) {
return arrRes[0].split("<").slice(-1)[0];
}
return null;
};

const getData = async (url) => {
const resp = await fetch(url, {
headers: {
// Add any necessary headers here
}
});
if (resp.status !== 200) {
throw Error(`Bad status getting branches ${resp.status} ${await resp.text()}`);
}
const data = await resp.json();
const mapped = data.map(item => ({
name: item.name,
sha: item.commit.sha,
isProtected: item.protected,
}));

const next = linkParser(resp.headers.get("Link"));
return { mapped, next };
};

// export const getBranches = async () => {
// let link = `${GITHUB_REPO_URI}/branches?per_page=100`;
// let final = [];

// while (link) {
// const { mapped, next } = await getData(link);
// link = next;
// final = final.concat(mapped);
// }
// return final;
// };

export async function getBranches(owner, repo) {
if (!gitHubInstance) {
gitHubInstance = await createGitHubInstance();
}
try {
// Generate a unique cache key for this file
const cacheKey = `github:getBranches:${owner}:${repo}`;

// Check if the content is in the cache
const cachedContent = await cacheRead(cacheKey);
if (cachedContent) {
console.info('[Github][getBranches][HIT]:',cacheKey )
// If the content was found in the cache, return it
// return cachedContent;
} else {
console.info('[Github][getBranches][Cache][MISS]:', cacheKey)
}

// Fetch branches
const branches = await gitHubInstance.paginate(gitHubInstance.repos.listBranches, {
owner,
repo,
per_page: 100
});

// Filter branches with protected set to false
const unprotectedBranches = branches.filter(branch => !branch.protected);

try {
// Store the content in the cache before returning it
await cacheWrite(cacheKey, unprotectedBranches, 600);
} catch (error) {
console.error(`[GitHub][getBranches] Error writing cache: ${error}`);

}
return unprotectedBranches;
} catch (error) {
console.error(`[GitHub][getBranches] Error getting sha: ${error}`);
// throw new Error(`[GitHub][getBranchSha] Could not get sha for branch`);
}
}
15 changes: 15 additions & 0 deletions pages/api/repo/get-branches.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// /pages/api/branches.js
import { getBranches } from "@/lib/github";

export default async (req, res) => {
try {
if (req && req.query && req.query.owner && req.query.repo) {
const branches = await getBranches(req.query.owner, req.query.repo);
res.status(200).json(branches);
} else {
res.status(500).json({ error: 'missing owner & repo' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
};

0 comments on commit 1e13914

Please sign in to comment.