Retrieve GitLab artifact files and save to disk using an access token via a webpage

Viewed 340

I'd like to do three things using a read-only access token, so that there is no need for the webpage user to provide Gitlab authentication. I must submit a GET request using the access token in the header, and haven't quite figured out how to handle the response in Javascript.

  1. Read the contents of a specific .JSON file in the artifacts path, and assign to a variable
  2. Trigger a download of a specific .XLSX file in the artifacts path, and save to disk
  3. Trigger a download of the full artifacts archive .ZIP, and save to disk

My code

    var myHeader = new Headers();
    myHeader.append("PRIVATE-TOKEN", accessToken);

    var myInit = { 
    method: 'GET',
    headers: myHeader
    };
    var myRequest = new Request(artifactPath, myInit);

    // response?

Documentation

Guidance provided for 1 and 2:

GET /projects/:id/jobs/artifacts/:ref_name/raw/*artifact_path?job=name
curl --location --header "PRIVATE-TOKEN: <your_access_token>"
    "https://gitlab.example.com/api/v4/projects/1/jobs/artifacts/master/raw/some/release/file.pdf?job=pdf"

Guidance provided for 3:

GET /projects/:id/jobs/artifacts/:ref_name/download?job=name
curl --header "PRIVATE-TOKEN: <your_access_token>"
    "https://gitlab.example.com/api/v4/projects/1/jobs/artifacts/master/download?job=test"

I'm under the impression that Ajax would help, which I have never used. All viable simplicity would be very much appreciated!

1 Answers

AJAX is possible with native JavaScript through 2 browser APIs.

You have XMLHttpRequest (older, more compatible, but ugly syntax):

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/path/to/get');
xhr.setRequestHeader('Your-Header-Name', 'Value');
xhr.onload = function() {
  // What this is depends on what kind of data the endpoint returned
  console.log(xhr.response);
}
xhr.send();

MDN reference

Modern JavaScript users typically prefer the Fetch API (newer, less compatible, clean syntax):

// Note this will contain some ES6 stuff, such as Promises
fetch('https://example.com/path/to/get', {
  // This is optional: method is GET by default
  method: 'GET',
  headers: {
    'Your-Header-Name': 'Value'
  }
}).then(res => 
  // You can do res.arrayBuffer(), .text(), but assuming the response is JSON...
  res.json()
).then(console.log);

MDN reference

I typically use fetch, but the method you use is mostly personal preference.

Related