-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub.jsx
More file actions
62 lines (58 loc) · 2.23 KB
/
github.jsx
File metadata and controls
62 lines (58 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const USERNAME = "nearbuilders"; // this could come from bos-workspace aliases...
const REPOSITORY = "bos-workspace-docs";
const BRANCH = "main";
const GITHUB_TOKEN = "YOUR_GITHUB_TOKEN";
const PATH_PREFIX = "md";
// Function to construct a GitHub API URL given a file path in a repository
const githubUrl = (path) =>
`https://raw.githubusercontent.com/${USERNAME}/${REPOSITORY}/${BRANCH}/${PATH_PREFIX}/${path}`;
// Function to retrieve data from GitHub given a file path
function get(path) {
const res = fetch(githubUrl(path), {
});
if (!res.ok) {
throw {
status: res.status,
message: `Failed to fetch ${path}: ${res.status} ${res.statusText}`
};
} else {
return res.body;
}
}
// Function to create and upload data to GitHub, returning a promise with the URL of the uploaded content
function create(path, data) {
// Added path to the parameters
return new Promise((resolve, reject) => {
if (data.length) {
const content = btoa(data); // Convert data to Base64 for GitHub API
asyncFetch(githubUrl(path), {
method: "PUT",
headers: {
Accept: "application/vnd.github.v3+json", // Set Accept header to expect JSON responses
Authorization: `token ${GITHUB_TOKEN}`, // Authorization header with your GitHub token
"Content-Type": "application/json", // Set the Content-Type header
},
body: JSON.stringify({
message: `Upload ${path}`, // Commit message
content: content, // Base64 encoded content
}),
})
.then((response) => response.json()) // Parse the JSON response
.then((data) => {
if (data.content && data.content.html_url) {
resolve({ url: data.content.html_url }); // Resolve the promise with the HTML URL of the new content
} else {
throw new Error("Invalid response from GitHub");
}
})
.catch((error) => {
console.error("Error in create function:", error);
reject(error); // Reject the promise in case of an error
});
} else {
reject("No data provided"); // Reject the promise if no data is provided
}
});
}
// Return the get and create functions for use elsewhere
return { get, create };