RESTful API for Git on Node.js with Express

Pavel Dzhagriev
CodeX
Published in
3 min readJul 25, 2021

Implementing a RESTful API over git repositories using Node.js can be a quick fix for tasks related to getting information about a git repository. Below is a description of creating an API using the Express framework.

To start, you need to add Express to the project, as well as the nodegit library, which provides a wrapper over the git CLI, the pg library to create a connection pool to the Postgre database (if links or repository names are stored in it), btoa — for encoding in BASE64, child_process — for executing bash commands on the server:

npm install express nodegit pg btoa child_process — save

After installation, we import the modules into the server.js file and describe the launch of the server on port 3031 (if a different port is not specified in the environment variables):

This example will look at the ability to work with multiple repositories. The list of repositories for which the API will be provided can be obtained in various available ways. Below is an example of how you can get a list of repositories directly from the database:

The YAMLconvert is function performs the YAML to JSON conversion here. As a result of execution, the repos array will contain a list of objects containing information about available repositories and data for authentication. In general, to work with a remote repository, it must be cloned to the node. To do this, let’s create a clone function:

The clone function uses the counter object to traverse the list of repositories and clone to the server. If cloning is supposed to be performed once at server start or upon request at the beginning of the user path, it is permissible to declare such an object inside the cloning request handler as in the example below:

This handler will be executed on a GET request along the path/git/api/clone, counter will contain the number of repositories already cloned from the list in the resolved field and will call the clone function until the entire list is traversed. However, in this case, inside the clone callback, we get an object that mutates outside. This behavior can negatively affect execution, so you can implement the counter object as an iterable:

Then in the clone function you can lines:

counter.resolved += 1;
counter.onResolve();

replace by:

counter.next();

After the repositories have already been cloned to the server, you can perform actions on them to obtain information about commits, branches, etc. For example, to get branches by the repository name with a GET request, you can implement the following:

Getting repository commits:

Get a list of files for a branch at a specific path in a paginated repository directory tree:

The walkTree function is needed to filter the list of files for the requested directory, since when the list is formed in eventEmmiter, file names are written with the full path from the root of the repository:

--

--