Giter Site home page Giter Site logo

jyothikrishna708 / node-gitlab Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jdalrymple/gitbeaker

0.0 1.0 0.0 5.08 MB

🤖 GitLab API NodeJS library with full support of all the Gitlab API services.

License: Other

JavaScript 2.72% Shell 2.32% Ruby 0.14% TypeScript 94.81%

node-gitlab's Introduction

npm @latest npm downloads dependencies Status devDependencies Status Greenkeeper badge Code Climate Build Status Coverage semantic-release Commitizen friendly Code Style: Prettier Install Size License: MIT

node-gitlab

🤖 GitLab API NodeJS library with full support of all the Gitlab API services.

Table of Contents

Install

# Install from npm
npm install gitlab

Getting Started

Instantiate the library using a basic token created in your Gitlab Profile

// ES6 (>=node 10.16.0 LTS)
import { Gitlab } from 'gitlab'; // All Resources
import { Projects } from 'gitlab'; // Just the Project Resource
//...etc

// ES5, assuming native or polyfilled Promise is available
const { Gitlab } = require('gitlab');
const api = new Gitlab({
  token: 'personaltoken',
});

Available instantiating options:

Name Optional Default Description
host Yes https://gitlab.com Gitlab Instance Host URL
token No* N/A Personal Token. Required (one of the three tokens are required)
oauthToken No* N/A OAuth Token. Required (one of the three tokens are required)
jobToken No* N/A CI Job Token. Required (one of the three tokens are required)
rejectUnauthorized Yes false Http Certificate setting
sudo Yes false Sudo query parameter
version Yes v4 API Version ID
camelize Yes false Response Key Camelize. Camelizes all response body keys
requester Yes KyRequester.ts Request Library Wrapper. Currently wraps Ky.
requestTimeout Yes 300000 Request Library Timeout in ms

CLI Support

The CLI export functions in a similar manner, following the pattern:

gitlab [service name] [method name] --arg1 --arg2 --arg3

Where service name is any of the supported API names, method name is any of the supported commands on that API service (See source for exceptions, but generally all, show, remove, update) and --arg1...--arg3 are any of the arguments you would normally supply to the function. The names of the args should match the names in the method headers EXCEPT all the optional arguments who's names should match what the GitLab API docs request.

There is one small exception with the instantiating arguments however, which must be supplied using a gl prefix. ie.

# To get all the projects
gitlab projects all --gl-token="personaltoken"

# To get a project with id = 2
gitlab projects show --gl-token="personaltoken" --projectId=2

To reduce the annoyance of having to pass those configuration properties each time, it is also possible to pass the token and host information through environment variables in the form of GITLAB_[option name] ie:

GITLAB_HOST=http://example.com
GITLAB_TOKEN=personaltoken

This could be set globally or using a .env file in the project folder.

Docs

Although there are the official docs for the API, there are some extra goodies offered by this package! After the 3.0.0 release, the next large project will be putting together proper documentation for these goodies [#39]! Stay tuned!!

Supported APIs

The API's that are currently supported are:

// General
ApplicationSettings
BroadcastMessages
Events
FeatureFlags
GeoNodes
GitignoreTemplates
GitLabCIYMLTemplates
Keys
Licence
LicenceTemplates
Lint
Markdown
Namespaces
NotificationSettings
PagesDomains
Search
SidekiqMetrics
Snippets
SystemHooks
Version
Wikis

// Groups
Groups
GroupAccessRequests
GroupBadges
GroupCustomAttributes
GroupIssueBoards
GroupMembers
GroupMilestones
GroupProjects
GroupVariables
GroupLabels
Epics
EpicIssues
EpicNotes
EpicDiscussions

// Projects
Branches
Commits
CommitDiscussions
ContainerRegistry
DeployKeys
Deployments
Environments
Issues
IssueAwardEmojis
IssueNotes
IssueDiscussions
Jobs
Labels
MergeRequests
MergeRequestAwardEmojis
MergeRequestDiscussions
MergeRequestNotes
Packages
Pipelines
PipelineSchedules
PipelineScheduleVariables
Projects
ProjectAccessRequests
ProjectBadges
ProjectCustomAttributes
ProjectImportExport
ProjectIssueBoards
ProjectHooks
ProjectMembers
ProjectMilestones
ProjectSnippets
ProjectSnippetNotes
ProjectSnippetDiscussions
ProjectSnippetAwardEmojis
ProtectedBranches
ProtectedTags
ProjectVariables
PushRules
Releases
ReleaseLinks
Repositories
RepositoryFiles
Runners
Services
Tags
Triggers

// Users
Users
UserEmails
UserImpersonationTokens
UserKeys
UserGPGKeys

Bundle Imports

It can be annoying to have to import all the API's pertaining to a specific resource. For example, the Projects resource is composed of many API's, Projects, Issues, Labels, MergeRequests, etc. For convenience, there is a Bundle export for importing and instantiating all these related API's at once.

import { ProjectsBundle } from 'gitlab';

const services = new ProjectsBundle({
  host:   'http://example.com',
  token: 'personaltoken'
})

services.Projects.all()
services.MergeRequests.all()
etc..

Currently there are three Bundles:

  1. ProjectsBundle which includes:
Branches
Commits
CommitDiscussions
Deployments
DeployKeys
Environments
Issues
IssueNotes
IssueDiscussions
IssueAwardEmojis
Jobs
Labels
MergeRequests
MergeRequestAwardEmojis
MergeRequestDiscussions
MergeRequestNotes
Packages
Pipelines
PipelineSchedules
PipelineScheduleVariables
Projects
ProjectAccessRequests
ProjectBadges
ProjectCustomAttributes
ProjectImportExport
ProjectIssueBoards
ProjectHooks
ProjectMembers
ProjectMilestones
ProjectSnippets
ProjectSnippetNotes
ProjectSnippetDiscussions
ProjectSnippetAwardEmojis
ProtectedBranches
ProtectedTags
ProjectVariables
PushRules
Repositories
RepositoryFiles
Runners
Services
Tags
Todos
Triggers
  1. UsersBundle which includes:
Users,
UserCustomAttributes,
UserEmails,
UserImpersonationTokens,
UserKeys,
UserGPGKeys
  1. GroupsBundle which includes:
Groups
GroupAccessRequests
GroupBadges
GroupCustomAttributes
GroupIssueBoards
GroupMembers
GroupMilestones
GroupProjects
GroupVariables
GroupLabels
Epics
EpicIssues
EpicNotes
EpicDiscussions

Examples

Once you have your library instantiated, you can utilize many of the API's functionality:

Using the await/async method

import { Gitlab } from 'gitlab';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

// Listing users
let users = await api.Users.all();

// Or using Promise-Then notation
api.Projects.all().then(projects => {
  console.log(projects);
});

General rule about all the function parameters:

  • If its a required parameter, it is a named argument in the functions
  • If its an optional parameter, it is defined in a options object following the named arguments

ie.

import { Gitlab } from 'gitlab';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

api.Projects.create({
  //options defined in the Gitlab API documentation
});

Pagination

For any .all() function on a resource, it will return all the items from Gitlab. This can be troublesome if there are many items, as the request it self can take a while to be fulfilled. As such, a maxPages option can be passed to limit the scope of the all function.

import { Gitlab } from 'gitlab';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

let projects = await api.Projects.all({ maxPages: 2 });

You can also use this in conjunction to the perPage argument which would override the default of 30 per page set by Gitlab:

import { Gitlab } from 'gitlab';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

let projects = await api.Projects.all({ maxPages: 2, perPage: 40 });

Additionally, if you would like to get back the pagination information, to know how many total pages there are for example, pass the pagination option showPagination in addition to either the maxPages or page properties.

...
const { data, pagination } = await api.Projects.all({
  perPage:40,
  maxPages:2,
  showPagination: true
});
...

This will result in a response in this format:

data: [
...
],
pagination: {
  total: 20,
  next: 4,
  current: 2,
  previous: 1,
  perPage: 3,
  totalPages: 3,
}

Note: supplying any pagination restrictions is call intensive. Some resources will require many requests which can put a significant load on the Gitlab Server. The general best practice would be setting the page request option to only return the first page if all results are not required.

Sudo

For private gitlab instances, administrators are able to impersonate users through the API. To do so, you have to set the 'Sudo' header on the services you want to impersonate the user for.

For example, if you want to disable notifications for a specific user:

import { NotificationSettings } from 'gitlab';

const service = new NotificationSettings({
  host:   'http://example.com',
  token: 'personaltoken'
  sudo: 8 // Can be the user ID or a username
});

await service.edit({
  level: NotificationSettings.LEVELS.DISABLED
})

Custom Request Libraries

There is another constructor parameter that allows the user to specify their own custom request library as long as it has a similar API to ky. To specify the library, simply set the requester property when instatiating a service:

An example can be seen in the KyRequester.ts file

import { Gitlab } from 'gitlab';
import YourCustomRequester from 'custom-requester';

const api = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
  requester: YourCustomRequester,
});

Misc

Handling HTTPS certificates

If your Gitlab server is running via HTTPS, the proper way to pass in your certificates is via a NODE_EXTRA_CA_CERTS environment key, like this:

"scripts": {
    "start": "NODE_EXTRA_CA_CERTS=./secrets/3ShapeCA.pem node bot.js"
},

NOTE: Using process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' will not work with the gitlab library. The rejectUnauthorized key is the only way to allow insecure certificates to be bypassed.

Non JSON/Text Responses

For responses such as file data that may be returned from the API, the data is exposed as a buffer. For example when trying to write a file, this can be done like:

let bufferedData = await api.Jobs.downloadLatestArtifactFile(project.id, "test", "job_test);

fs.writeFileSync("test.zip", bufferedData);

Development

To get this running locally rather than from your node_modules folder:

$ git clone https://github.com/jdalrymple/node-gitlab.git
$ cd node-gitlab
$ npm install
$ npm run-script build

And then inside whatever project you are using node-gitlab in you change your references to use that repo. In your package.json of that upstream project change:

"dependencies": {
  "gitlab": "5.0.0"
}

to this

"dependencies": {
  "gitlab": "<path-to-your-clone>"
}

Testing

Testing is a work-in-progress right now but here is the start.

  1. First run Gitlab in a docker container:
docker-compose -f docker-compose.test.yml up
  1. Once GitLab is up on localhost:8080, get the two environment variables from the docker image could either export them into environment variables locally:
export PERSONAL_ACCESS_TOKEN=$(docker exec -it gitlab bash -lc 'printf "%q" "${PERSONAL_ACCESS_TOKEN}"')
export GITLAB_URL=$(docker exec -it gitlab bash -lc 'printf "%q" "${GITLAB_URL}"')
  1. Now run the tests
npm run test

# or, alternatively
npm run test-with-token # sets PERSONAL_ACCESS_TOKEN and GITLAB_URL from above, before running tests

You can also define them in front of the npm script

PERSONAL_ACCESS_TOKEN='abcdefg' GITLAB_URL='http://localhost:8080' npm run test

Note it may take about 3 minutes to get the variables while Gitlab is starting up in the container

Contributors

This started off as a fork from node-gitlab but I ended up rewriting much of the code. Here are the original work's contributors.

License

MIT

Changelog

Here

node-gitlab's People

Contributors

jdalrymple avatar greenkeeper[bot] avatar semantic-release-bot avatar pablobirukov avatar jetersen avatar mr-wallet avatar zackurben avatar giuseppeangri avatar musinux avatar max-wittig avatar danielrose avatar kyr avatar martinbenninger avatar spurdy avatar fewieden avatar arsdehnel avatar salimlou avatar marethyu1 avatar rkrasiuk avatar codejennerator avatar icanhasjonas avatar comster avatar ikatsuba avatar claude-abounegm avatar buffcode avatar leipert avatar muniftanjim avatar niklas-dahl avatar gpineda-dev avatar qkdreyer avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.