Github API
-
Environment Variables
-
.env
GIT_TOKEN=token123
GIT_ACCOUNT_NAME=fresher-batch-2021
Task 1: Github Controller
import { Controller, Query, Delete, Get, HttpCode, Param,Patch, Req, Res, Logger } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { GithubService } from './github.service';
import { Repository } from './repository';
import {HttpService} from '@nestjs/axios';
@ApiTags('Github')
@Controller('api/v1/github')
export class GithubController {
private readonly logger = new Logger(GithubController.name);
github_client_id = "";
github_client_secret = "";
constructor(private readonly githubService: GithubService,
private httpService: HttpService){
}
@Get(':owner/:repo')
@HttpCode(200)
async getRepositoryDetails(@Param('owner') owner:string, @Param('repo') repo:string) {
try{
const {data:repository} = await this.githubService.getRepository(owner, repo);
const {data:branches} = await this.githubService.getBranches(owner, repo);
const {data:commits} = await this.githubService.getCommits(owner, repo);
const {data:collaborators} = await this.githubService.getCollaborators(owner, repo);
return Repository.toRepo(repository,branches,commits, collaborators);
}catch(err){
this.logger.debug(err);
return err;
}
}
@Patch(':owner/:repo/:username')
@HttpCode(200)
async addCollaborator(@Param('owner') owner:string, @Param('repo') repo:string,
@Param('username') username:string) {
try{
{data} = await this.githubService.addCollaborator(owner, repo,username);
return data;
}catch(err){
this.logger.debug(err);
return err;
}
}
@Delete(':owner/:repo/:username')
@HttpCode(200)
async removeCollaborator(@Param('owner') owner:string, @Param('repo') repo:string,
@Param('username') username:string) {
try{
const {data} = await this.githubService.removeCollaborator(owner, repo,username);
return data;
}catch(err){
this.logger.debug(err);
return err;
}
}
}
Task 2: GithubService
import { Injectable, Logger } from "@nestjs/common";
import { Octokit } from "@octokit/rest";
import axios from "axios";
import {HttpService} from '@nestjs/axios';
@Injectable()
export class GithubService {
private readonly logger = new Logger(GithubService.name);
token = "token123";
GIT_ACCOUNT_NAME = "csys-fresher-batch-2021";
HOOK_EVENT_URL = process.env.PROJECT_EVENT_API;
getHeaders() {
return {
"User-Agent": "app",
"Authorization": `Bearer ${this.token}`,
"Accept": "application/json",
"Content-Type": "application/json"
}
};
getPreviewHeaders() {
return {
"User-Agent": "app",
"Authorization": `Bearer ${this.token}`,
"Accept": "application/vnd.github.inertia-preview+json",
"Content-Type": "application/json"
}
};
getHeaders1() {
return {
"User-Agent": "app",
"Authorization": `Bearer ${this.token}`,
"Accept": "application/vnd.github.v3+json",
"Content-Type": "application/json"
}
};
/*
static projectHeaders = {
"User-Agent": "app",
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github.inertia-preview+json",
"Content-Type": "application/json",
};
*/
apiUrl = "https://api.github.com";
octokit:Octokit;
instance:any;
constructor(private readonly httpService: HttpService) {
this.instance = axios.create({
baseURL: 'https://api.github.com/',
headers: this.getHeaders()
});
this.octokit = new Octokit({
userAgent:'pt',
token: this.token,
baseUrl: "https://api.github.com"
});
//this.logger.debug(this.octokit);
}
getHeaders2() {
return {
"user-agent":'pt',
//"authorization": `token #{this.token}`,
};
}
getCollaborator(account, repoName) {}
async getRepository(owner:string, repo:string){
// let url = `GET /repos/{owner}/{repo}`;
// return await this.octokit.request(url,{
// headers: this.getHeaders2(),
// owner: owner,
// repo: repo
// });
return await this.instance.get(this.apiUrl + "/repos/" + owner + "/" + repo);
}
async getBranches(owner:string, repo:string){
return await this.instance.get(this.apiUrl + `/repos/${owner}/${repo}/branches`);
}
async getCommits(owner:string, repo:string){
return await this.instance.get(this.apiUrl + `/repos/${owner}/${repo}/commits`);
}
async getCollaborators(owner:string, repo:string){
return await this.instance.get(this.apiUrl + `/repos/${owner}/${repo}/collaborators`)
}
getRepositories() {
this.octokit.rest.repos
.listForOrg({ org: "octokit", type: "public" })
.then(({ data }) => {
// handle data
});
}
async addCollaborator(owner: string, repo: string, username: string) {
this.logger.debug(owner +"-" + repo + "-" + username);
return await axios.put(this.apiUrl + `/repos/${owner}/${repo}/collaborators/${username}`,{}, { headers: this.getPreviewHeaders()});
}
async removeCollaborator(owner: string, repo: string, username: string) {
this.logger.debug(owner +"-" + repo + "-" + username);
return await axios.delete(this.apiUrl + `/repos/${owner}/${repo}/collaborators/${username}`, { headers: this.getPreviewHeaders()});
}
}
/*
const request = require("superagent");
const token = process.env.GIT_TOKEN;
class GithubService {
static async createRepo(repo) {
let repoData = {
name: repo.name,
private: repo.private ? repo.private : false,
auto_init: repo.init ? repo.init : true,
has_issues: true,
has_projects: true,
};
let url = `${this.apiUrl}user/repos`;
return request.post(url, repoData).set(this.headers);
}
static async getAllRepos(account, pageNo = 1) {
let url = `${this.apiUrl}users/${account}/repos?page=${pageNo}`;
return request.get(url).set(this.headers);
}
static async getRepository(account, repoName) {
let url = `${this.apiUrl}repos/${account}/${repoName}`;
return request.get(url).set(this.headers);
}
static async getRepositoryBranches(account, repoName) {
let url = `${this.apiUrl}repos/${account}/${repoName}/branches`;
return request.get(url).set(this.headers);
}
static async getRepositoryEvents(account, repoName) {
let url = `${this.apiUrl}repos/${account}/${repoName}/events`;
return request.get(url).set(this.headers);
}
static async getRepositoryCollaborators(account, repoName) {
let url = `${this.apiUrl}repos/${account}/${repoName}/collaborators`;
return request.get(url).set(this.headers);
}
static async addBoardCollaborator(projectId, username, permission='read') {
let url = `${this.apiUrl}projects/${projectId}/collaborators/${username}`;
let permissionData = {"permission": permission}
return request.put(url, permissionData).set(this.projectHeaders);
}
static async addCollaborator(account, repoName, username) {
let url = `${this.apiUrl}repos/${account}/${repoName}/collaborators/${username}`;
return request.put(url, null).set(this.headers);
}
static async createProject(projectBoard) {
let url = `${this.apiUrl}user/projects`;
return request.post(url, projectBoard).set(this.projectHeaders);
}
static async updateProject(projectId) {
//let url = `${this.apiUrl}repos/${account}/${repoName}/projects`;
let url = `${this.apiUrl}projects/${projectId}`;
this.logger.debug(url);
let data = { private: false};
return request.patch(url, data).set(this.projectHeaders);
}
static async createProjectColumn(projectId, columnName) {
let url = `${this.apiUrl}projects/${projectId}/columns`;
this.logger.debug(url);
let column = { name: columnName};
return request.post(url, column).set(this.projectHeaders);
}
static async createHook(account, repoName) {
let hook = {
name: "web",
config: {
url: process.env.PROJECT_EVENT_API,
content_type: "json",
insecure_ssl: 1,
},
active: true,
events: ["push", "pull_request","pull_request_review","pull_request_review_comment", "commit_comment","issue_comment","member", "issues","create","delete","milestone","repository","project"],
};
let url = `${this.apiUrl}repos/${account}/${repoName}/hooks`;
this.logger.debug(url);
return request.post(url, hook).set(this.projectHeaders);
}
static async deleteHook(account, repoName, id) {
let url = `${this.apiUrl}repos/${account}/${repoName}/hooks/${id}`;
return request.delete(url).set(this.projectHeaders);
}
static async getRepositoryIssues(account, repoName) {
let url = `${this.apiUrl}repos/${account}/${repoName}/issues`;
return request.get(url).set(this.headers);
}
static async createFile(account, repoName, content) {
let committer = { name: "Bot", email: "naresh.20201012@gmail.com" };
content["committer"] = committer;
let url = `${this.apiUrl}repos/${account}/${repoName}/contents/${content.fileName}`;
return request.put(url, content).set(this.headers);
}
static async deleteFile(account, repoName, fileName) {
let url = `${this.apiUrl}repos/${account}/${repoName}/contents/${fileName}`;
return request.delete(url, content).set(this.headers);
}
///users/{username}
//application/vnd.github.v3+json
static async updateRepo(account, repoName, content) {
let url = `${this.apiUrl}repos/${account}/${repoName}`;
return request.patch(url, content).set(this.headers);
}
static async createMilestone(account, repoName, milestone) {
let url = `${this.apiUrl}repos/${account}/${repoName}/milestones`;
return request.post(url, milestone).set(this.headers);
}
static async getMilestones(account, repoName, milestone) {
let url = `${this.apiUrl}repos/${account}/${repoName}/milestones`;
return request.get(url).set(this.headers);
}
static async createIssue(fullRepoName, issue) {
let url = `${this.apiUrl}repos/${fullRepoName}/issues`;
return request.post(url, issue).set(this.headers);
}
static async getIssue(fullRepoName, id) {
let url = `${this.apiUrl}repos/${fullRepoName}/issues/${id}`;
return request.get(url).set(this.headers);
}
static async getIssues(fullRepoName) {
let url = `${this.apiUrl}repos/${fullRepoName}/issues`;
return request.get(url).set(this.headers);
}
static async getMilestone(account, repoName, milestoneNo) {
let url = `${this.apiUrl}repos/${account}/${repoName}/milestones/${milestoneNo}`;
return request.get(url).set(this.headers);
}
static async deleteMilestone(account, repoName, milestoneNo) {
let url = `${this.apiUrl}repos/${account}/${repoName}/milestones/${milestoneNo}`;
return request.delete(url).set(this.headers);
}
///repos/{owner}/{repo}
}
exports.GithubService = GithubService;
*/