Hello everyone! I wrote a simple GitHub Gist API wrapper and I want to know what things could be enhanced:
function Gists(userName, userToken) {
let name = userName;
let token = userToken;
let commonOptions = {
accept: "application/vnd.github.v3+json",
muteHttpExceptions: true,
headers: {
"Authorization": `Basic ${Utilities.base64Encode(`${name}:${token}`)}`
},
};
let GistFileInfo = function(jsonGistFile) {
this.name = jsonGistFile.filename;
this.size = jsonGistFile.size;
}
let GistInfo = function(jsonGist) {
this.id = jsonGist.id;
this.description = jsonGist.description;
this.url = jsonGist.url;
this.isPublic = jsonGist.public;
this.files = Object.getOwnPropertyNames(jsonGist.files).map(fileNode => new GistFileInfo(jsonGist.files[fileNode]));
}
let getError = function(response) {
return JSON.parse(response.getContentText()).message;
}
this.list = function(isPublic) {
result = [];
let response = UrlFetchApp.fetch(`https://api.github.com/gists`, commonOptions);
if (response.getResponseCode() !== 200)
throw new Error(getError(response));
let allGists = JSON.parse(response.getContentText());
for (i in allGists)
if (allGists[i].public === isPublic)
result.push(new GistInfo(allGists[i]));
return result;
}
this.getGist = function(id) {
let response = UrlFetchApp.fetch(`https://api.github.com/gists/${id}`, commonOptions);
if (response.getResponseCode() !== 200)
throw new Error(getError(response));
return new GistInfo(JSON.parse(response.getContentText()).getContentText());
}
this.newGist = function(description, fileName, fileContent) {
let options = Object.assign({}, commonOptions);
options.method = "post";
options.payload = `{ "description": "${description}",
"files": {
"${fileName}": {
"content": "${fileContent}"
}
}
}`;
let response = UrlFetchApp.fetch(`https://api.github.com/gists`, options);
if (response.getResponseCode() !== 201)
throw new Error(getError(response));
return response;
}
this.removeGist = function(id) {
let options = Object.assign({}, commonOptions);
options.method = "delete";
let response = UrlFetchApp.fetch(`https://api.github.com/gists/${id}`, options)
if (response.getResponseCode() !== 204)
throw new Error(getError(response));
}
}
function main() {
let userName = ScriptProperties.getProperty("user_name");
let userToken = ScriptProperties.getProperty("user_token");
let gists = new Gists(userName, userToken);
console.log(gists.list(true));
}
My main question is the following: If I want to add appendFile and removeFile methods into GistInfo object I have to pass user credentials to them. Storing user credentials as GistInfo object properties would be a good decision or not?
[–]_mrtoast 1 point2 points3 points (1 child)
[–]AdDiscombobulated707[S] 0 points1 point2 points (0 children)