How to use the @octokit/rest.plugin function in @octokit/rest

To help you get started, we’ve selected a few @octokit/rest examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github node-gh / gh / src / github.ts View on Github external
github_user: user,
        api: { protocol, pathPrefix, host },
    } = config

    const isEnterprise = host !== 'api.github.com'

    const apiUrl = `${protocol}://${isEnterprise ? host : 'api.github.com'}`

    const { href } = new URL(`${apiUrl}${pathPrefix || ''}`)

    // trim trailing slash for Octokit
    const baseUrl = href.replace(/\/+$/, '')

    const throttlePlugin = await import('@octokit/plugin-throttling')

    Octokit.plugin(throttlePlugin)

    return new Octokit({
        // log: console,
        baseUrl,
        auth: await getToken({ token, user }),
        throttle: {
            onRateLimit: (retryAfter, options) => {
                console.warn(`Request quota exhausted for request ${options.method} ${options.url}`)

                if (options.request.retryCount === 0) {
                    // only retries once
                    console.log(`Retrying after ${retryAfter} seconds!`)
                    return true
                }
            },
            onAbuseLimit: (_, options) => {
github balena-io / balena-cli / automation / deploy-bin.ts View on Github external
function getOctokit(): any {
	if (cachedOctokit) {
		return cachedOctokit;
	}
	const Octokit = require('@octokit/rest').plugin(
		require('@octokit/plugin-throttling'),
	);
	return (cachedOctokit = new Octokit({
		auth: GITHUB_TOKEN,
		throttle: {
			onRateLimit: (retryAfter: number, options: any) => {
				console.warn(
					`Request quota exhausted for request ${options.method} ${
						options.url
					}`,
				);
				// retries 3 times
				if (options.request.retryCount < 3) {
					console.log(`Retrying after ${retryAfter} seconds!`);
					return true;
				}
github fwouts / prmonitor / src / github-api / implementation.ts View on Github external
import Octokit from "@octokit/rest";
import { GitHubApi } from "./api";

const ThrottledOctokit = Octokit.plugin(require("@octokit/plugin-throttling"));

interface ThrottlingOptions {
  method: string;
  url: string;
  request: {
    retryCount: number;
  };
}

export function buildGitHubApi(token: string): GitHubApi {
  const octokit = new ThrottledOctokit({
    auth: `token ${token}`,
    // https://developer.github.com/v3/pulls/#list-pull-requests
    // Enable Draft Pull Request API.
    previews: ["shadow-cat"],
    throttle: {
github firebase / oss-bot / functions / src / github.ts View on Github external
* You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import * as log from "./log";
import * as util from "./util";
import * as Octokit from "@octokit/rest";

const OctokitRetry = require("@octokit/plugin-retry");
const GithubApi = require("@octokit/rest").plugin(OctokitRetry);

/**
 * Get a new client for interacting with Github.
 * @param {string} token Github API token.
 */
export class GithubClient {
  private token: string;
  private api: Octokit;

  constructor(token: string) {
    // Github API token
    this.token = token;

    // Underlying Github API client
    this.api = new GithubApi({
      timeout: 10000
github artsy / dupe-report / packages / dupe-report / src / api / github.ts View on Github external
import retry from "@octokit/plugin-retry";
import throttling from "@octokit/plugin-throttling";
import GitHubApi from "@octokit/rest";
import { URL } from "url";

import { safelyFetchEnvs } from "../lib/envs";

const repo = ({ owner, repo }: Partial) =>
  `https://github.com/${owner}/${repo}`;

// @ts-ignore
const GitHubWithPlugins = GitHubApi.plugin(throttling).plugin(retry);

const { GH_TOKEN } = safelyFetchEnvs(["GH_TOKEN"]);

interface IssueOptions {
  owner: string;
  repo: string;
  number: number;
}

type GitHubOptions = Partial & {
  dryRun: boolean;
  owner: string;
  repo: string;
  pullRequest: string;
};
github octokit / plugin-throttling.js / test / integration / octokit.js View on Github external
const Octokit = require('@octokit/rest')
const { RequestError } = require('@octokit/request-error')
const throttlingPlugin = require('../..')

module.exports = Octokit
  .plugin((octokit) => {
    octokit.__t0 = Date.now()
    octokit.__requestLog = []
    octokit.__requestTimings = []

    octokit.hook.wrap('request', async (request, options) => {
      octokit.__requestLog.push(`START ${options.method} ${options.url}`)
      octokit.__requestTimings.push(Date.now() - octokit.__t0)
      await new Promise(resolve => setTimeout(resolve, 0))

      const res = options.request.responses.shift()
      if (res.status >= 400) {
        const message = res.data.message != null ? res.data.message : `Test failed request (${res.status})`
        const error = new RequestError(message, res.status, {
          headers: res.headers,
          request: options
github lightness / github-repo-tools / src / modules / octokit / octokit.service.ts View on Github external
public getOctokit(token?: string) {
    return new (Octokit.plugin(RetryPlugin))({
      auth: token,
      retry: {
        doNotRetry: [404],
      }
    });
  }
github mozillach / gh-projects-content-queue / lib / accounts / github.js View on Github external
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
/**
 * @module accounts/github
 * @license MPL-2.0
 */
"use strict";

const GitHub = require("@octokit/rest")
    .plugin(require("@octokit/plugin-retry"))
    .plugin(require("@octokit/plugin-throttling"));

const MAX_RETRIES = 5;

class GitHubAccount {
    constructor(config) {
        const ghClient = new GitHub({
            auth: `token ${config.token}`,
            throttle: {
                onRateLimit: (retryAfter, options) => {
                    console.warn(`Request quota exhausted for request ${options.method} ${options.url}`);

                    if (options.request.retryCount < MAX_RETRIES) {
                        console.log(`Retrying after ${retryAfter} seconds!`);
                        return true;
github pkgjs / statusboard / lib / github.js View on Github external
'use strict'
const inquirer = require('inquirer')
const fetch = require('node-fetch')
const Octokit = require('@octokit/rest')
  .plugin(require('@octokit/plugin-throttling'))
  .plugin(require('@octokit/plugin-retry'))

module.exports =
async function getOctokit (opts = {}) {
  let {
    token,
    username,
    password,
    tfatoken,
    log,
    onAbuseLimit,
    onRateLimit
  } = opts

  let prompts = {}