gitlab_service.js 2.0 KB
Newer Older
1 2 3 4 5 6 7 8
const request = require('request-promise');
const gitService = require('./git_service');
const apiRoot = 'https://gitlab.com/api/v4'; // FIXME: Get domain dynamically

async function fetch(path) {
  const config = {
    url: `${apiRoot}${path}`,
    headers: {
F
Fatih Acet 已提交
9
      'PRIVATE-TOKEN': 'f9vX_GfmWc_SLzz7Siaq', // FIXME: Make token UI
10 11 12 13 14 15 16 17 18 19 20 21
    }
  };

  const response = await request(config);

  try {
    return JSON.parse(response);
  } catch (e) {
    return { error: e };
  }
}

F
Fatih Acet 已提交
22 23
// FIXME: Don't rely on `created-by-me`. It doesn't have to be my own MR.
// Currently GL API doesn't support finding MR by branch name or commit id.
24
async function fetchMyOpenMergeRequests() {
F
Fatih Acet 已提交
25 26 27 28 29 30 31
  const project = await fetchCurrentProject();

  if (project) {
    return await fetch(`/projects/${project.id}/merge_requests?scope=created-by-me&state=opened`);
  }

  return null;
32 33 34 35
}

async function fetchOpenMergeRequestForCurrentBranch() {
  const branchName = await gitService.fetchBranchName();
F
Fatih Acet 已提交
36
  const mrs = await fetchMyOpenMergeRequests();
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

  return mrs.filter(mr => mr.source_branch === branchName)[0];
}

async function fetchLastPipelineForCurrentBranch() {
  const mr = await fetchOpenMergeRequestForCurrentBranch();

  if (mr) {
    const path = `/projects/${mr.target_project_id}/pipelines`;
    const branchName = await gitService.fetchBranchName();
    const pipelines = await fetch(`${path}?ref=${branchName}`);

    if (pipelines.length) {
      return await fetch(`${path}/${pipelines[0].id}`);
    }

    return null;
  }

  return null;
}

F
Fatih Acet 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
async function fetchCurrentProject() {
  const remote = await gitService.fetchGitRemote();

  if (remote) {
    const { namespace, project } = remote;
    const projectData = await fetch(`/projects/${namespace}%2F${project}`);

    return projectData || null;
  }

  return null;
}

72 73 74
exports.fetchMyOpenMergeRequests = fetchMyOpenMergeRequests;
exports.fetchOpenMergeRequestForCurrentBranch = fetchOpenMergeRequestForCurrentBranch;
exports.fetchLastPipelineForCurrentBranch = fetchLastPipelineForCurrentBranch;
F
Fatih Acet 已提交
75
exports.fetchCurrentProject = fetchCurrentProject;