40.0.3 • Published 22 days ago

@gitbeaker/rest v40.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
22 days ago

A Typed GitLab SDK for Browsers, Node.js, and Deno.

Table of Contents

Features

  • Complete - All features of Gitlab's exposed APIs are covered up to version 16.5. See here for the full list.
  • Universal - Works in all modern browsers, Node.js, and Deno.
  • Tested - All libraries have > 80% test coverage.
  • Typed - All libraries have extensive TypeScript declarations.

Usage

<script type="module">
  import { Gitlab } from 'https://esm.sh/@gitbeaker/rest';
</script>
import { Gitlab } from 'https://esm.sh/@gitbeaker/rest?dts';

Install with npm install @gitbeaker/rest, or yarn add @gitbeaker/rest

import { Gitlab } from '@gitbeaker/rest';

API Client

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

const api = new Gitlab({
  token: 'personaltoken',
});

Available instantiating options:

NameOptionalDefaultDescription
hostYeshttps://gitlab.comGitlab Instance Host URL
tokenNo*N/APersonal Token. Required (one of the three tokens are required)
oauthTokenNo*N/AOAuth Token. Required (one of the three tokens are required)
jobTokenNo*N/ACI Job Token. Required (one of the three tokens are required)
rejectUnauthorizedYestrueHttp Certificate setting, Only applies to non-browser releases and HTTPS hosts urls
sudoYesfalseSudo query parameter
camelizeYesfalseCamelizes all response body keys
requesterFnNo@gitbeaker/rest & @gitbeaker/cli : fetch-based, The @gitbeaker/core package does not have a default and thus must be set explicitlyRequest Library Wrapper
queryTimeoutYes300000Query Timeout in ms
profileTokenYesN/ARequests Profiles Token
profileModeYesexecutionRequests Profiles Token
rateLimitsNoDEFAULT_RATE_LIMITSGlobal and endpoint specific adjustable rate limits

*One of these options must be supplied.

Expanded Payloads

For simplicity, only the response body is returned from the API methods. However, seeing additional response fields, such as the status, headers, etc., may be helpful. For this purpose, an additional optional parameter, showExpanded can be passed for most API methods.

For methods that return non-paginated results, the payload has this structure:

type ResponseBodyTypes =
  | Record<string, unknown>
  | Record<string, unknown>[]
  | ReadableStream
  | Blob
  | string
  | string[]
  | number
  | void
  | null;

interface FormattedResponse<T extends ResponseBodyTypes = ResponseBodyTypes> {
  body: T;
  headers: Record<string, string>;
  status: number;
}

For methods that return paginated results, the payload also includes paginated information outlined in the Pagination documentation

Pagination

Available pagination options:

NameKeysetOffsetTypeDefaultDescription
paginationXX'offset' or 'keyset''offset'Defines which pagination type should be used
perPageXXNumber20Amount of results per request
orderByXStringWhat field the results should be ordered by
sortX'asc' or 'desc''asc'The direction of sort for the results
maxPagesXNumberN/AMaximum amount of requests that should be made
pageXNumberN/ASpecific page to be retrieved
showExpandedXBooleanfalseReturns with the pagination information in addition to the data

Offset 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 itself 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 '@gitbeaker/rest';

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 with the perPage argument which would override the default of 30 per page set by Gitlab:

import { Gitlab } from '@gitbeaker/rest';

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 option showExpanded. If there are multiple results the pagination property will be included as shown below:

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

This will result in a response in this format:

data: [
...
],
paginationInfo: {
  next: 4,
  current: 2,
  previous: 1,
  perPage: 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.

Keyset Pagination

Similarly, support for Keyset pagination can be toggled on by passing a pagination parameter as a query option

const { data } = await api.Projects.all({
  pagination: 'keyset',
  sort: 'asc',
  orderBy: 'created_at',
});

Rate Limits

Rate limits are completely customizable, and are used to limit the request rate between consecutive API requests within the library. By default, all non-specified endpoints use a 3000 rps rate limit, while some endpoints have much smaller rates as dictated by the Gitlab Docs. See below for the default values:

const DEFAULT_RATE_LIMITS = Object.freeze({
  // Default rate limit
  '**': 3000,

  // Import/Export
  'projects/import': 6,
  'projects/*/export': 6,
  'projects/*/download': 1,
  'groups/import': 6,
  'groups/*/export': 6,
  'groups/*/download': 1,

  // Note creation
  'projects/*/issues/*/notes': {
    method: 'post',
    limit: 300,
  },
  'projects/*/snippets/*/notes': {
    method: 'post',
    limit: 300,
  },
  'projects/*/merge_requests/*/notes': {
    method: 'post',
    limit: 300,
  },
  'groups/*/epics/*/notes': {
    method: 'post',
    limit: 300,
  },

  // Repositories - get file archive
  'projects/*/repository/archive*': 5,

  // Project Jobs
  'projects/*/jobs': 600,

  // Member deletion
  'projects/*/members': 60,
  'groups/*/members': 60,
});

Rate limits can be overridden when instantiating a API wrapper. For ease of use, these limits are configured using glob patterns, and can be formatted in two ways.

  1. The glob for the endpoint with the corresponding rate per second
  2. The glob for the endpoint, with an object specifying the specific method for the endpoint and the corresponding rate limit
const api = new Gitlab({
  token: 'token',
  rateLimits: {
    '**': 30,
    'projects/import/*': 40,
    'projects/*/issues/*/notes': {
      method: 'post',
      limit: 300,
    },
  },
});

Error Handling

Request errors are returned back within a plain Error instance, using the cause to hold the original response and a text description of the error pulled from the response's error or message fields if JSON, or its plain text value:

class GitbeakerError extends Error {
  constructor(
    message: string,
    options?: {
      cause: {
        description: string;
        request: Request;
        response: Response;
      };
    },
  ) {
    super(message, options);
    this.name = 'GitbeakerError';
  }
}

Note, the message is assigned to the Response's statusText, and the Request and Response types are from the NodeJS API.

Examples

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

Using the await/async method

import { Gitlab } from '@gitbeaker/rest';

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);
});

A general rule about all the function parameters:

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

ie.

import { Projects } from '@gitbeaker/rest';

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

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

Contributors

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

40.0.3

22 days ago

40.0.2

1 month ago

40.0.1

2 months ago

40.0.0

2 months ago

39.34.3

2 months ago

39.34.2

3 months ago

39.33.2

3 months ago

39.33.1

3 months ago

39.34.1

3 months ago

39.34.0

3 months ago

39.33.0

3 months ago

39.31.1

3 months ago

39.31.0

3 months ago

39.32.0

3 months ago

39.30.0

4 months ago

39.29.0

4 months ago

39.28.0

4 months ago

39.27.1

4 months ago

39.27.0

4 months ago

39.26.2

5 months ago

39.26.1

5 months ago

39.26.0

5 months ago

39.25.1

5 months ago

39.9.0

9 months ago

39.7.0

10 months ago

39.18.0

7 months ago

39.5.1

10 months ago

39.5.0

10 months ago

39.16.0

7 months ago

39.10.3

9 months ago

39.14.0

8 months ago

39.10.1

9 months ago

39.12.0

9 months ago

39.10.2

9 months ago

39.10.0

9 months ago

39.24.0

6 months ago

39.22.0

6 months ago

39.20.0

7 months ago

39.19.0

7 months ago

39.8.0

10 months ago

39.17.0

7 months ago

39.6.0

10 months ago

39.15.0

8 months ago

39.13.0

8 months ago

39.11.0

9 months ago

39.25.0

5 months ago

39.21.1

7 months ago

39.23.0

6 months ago

39.21.2

6 months ago

39.21.0

7 months ago

39.4.0

10 months ago

39.3.0

10 months ago

39.2.0

10 months ago

39.1.1

10 months ago

39.1.0

11 months ago

39.0.0

11 months ago

38.11.0

11 months ago

38.12.1

11 months ago

38.12.0

11 months ago

38.6.0

12 months ago

38.3.0

12 months ago

38.5.0

12 months ago

38.4.0

12 months ago

38.1.0

1 year ago

38.0.1

1 year ago

38.2.0

1 year ago

38.1.1

1 year ago

38.0.0

1 year ago

37.0.0

1 year ago

37.1.0

1 year ago

38.10.0

11 months ago

38.8.0

12 months ago

38.7.0

12 months ago

38.9.0

11 months ago

36.0.1-next.1

1 year ago

36.0.1-next.0

1 year ago

36.0.0-rc.2

1 year ago

36.0.0-rc.1

1 year ago

36.0.0-rc.0

1 year ago