@octokit/request#request JavaScript Examples

The following examples show how to use @octokit/request#request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From verify-linked-issue-action with MIT License 6 votes vote down vote up
constructor(request, headers, response) {
        super(_buildMessageForResponseErrors(response));
        this.request = request;
        this.headers = headers;
        this.response = response;
        this.name = "GraphqlResponseError";
        // Expose the errors and response data in their shorthand properties.
        this.errors = response.errors;
        this.data = response.data;
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
Example #2
Source File: index.js    From deploy-gae-action with MIT License 6 votes vote down vote up
constructor(request, response) {
        const message = response.data.errors[0].message;
        super(message);
        Object.assign(this, response.data);
        this.name = "GraphqlError";
        this.request = request;
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
Example #3
Source File: index.js    From ipfs-action with MIT License 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint,
    });
}
Example #4
Source File: index.js    From deploy-gae-action with MIT License 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint,
    });
}
Example #5
Source File: index.js    From ipfs-action with MIT License 6 votes vote down vote up
constructor(request, response) {
        const message = response.data.errors[0].message;
        super(message);
        Object.assign(this, response.data);
        Object.assign(this, { headers: response.headers });
        this.name = "GraphqlError";
        this.request = request;
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
Example #6
Source File: index.js    From compute-tag with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
constructor(request, response) {
        const message = response.data.errors[0].message;
        super(message);
        Object.assign(this, response.data);
        Object.assign(this, { headers: response.headers });
        this.name = "GraphqlError";
        this.request = request;
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
Example #7
Source File: index.js    From random-rickroll with Apache License 2.0 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint,
    });
}
Example #8
Source File: index.js    From compute-tag with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint,
    });
}
Example #9
Source File: index.js    From discord-commits with MIT License 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint,
    });
}
Example #10
Source File: index.js    From dotnet-bump-version with MIT License 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint,
    });
}
Example #11
Source File: index.js    From payload-info-action with MIT License 6 votes vote down vote up
function graphql(request, query, options) {
    options =
        typeof query === "string"
            ? (options = Object.assign({ query }, options))
            : (options = query);
    const requestOptions = Object.keys(options).reduce((result, key) => {
        if (NON_VARIABLE_OPTIONS.includes(key)) {
            result[key] = options[key];
            return result;
        }
        if (!result.variables) {
            result.variables = {};
        }
        result.variables[key] = options[key];
        return result;
    }, {});
    return request(requestOptions).then(response => {
        if (response.data.errors) {
            throw new GraphqlError(requestOptions, {
                data: response.data
            });
        }
        return response.data.data;
    });
}
Example #12
Source File: index.js    From zcl-eth-key-converter with MIT License 6 votes vote down vote up
createBasicAuth = function createBasicAuth(options) {
    console.warn(`[@octokit/auth-basic] Basic authentication has been deprecated. See https://github.com/octokit/auth-basic.js/#deprecation`);
    ["username", "password", "on2Fa"].forEach((option) => {
        if (!options.hasOwnProperty(option)) {
            throw new Error(`[@octokit/auth-basic] ${option} option is required`);
        }
    });
    const strategyOptions = Object.assign({
        token: {},
    }, options);
    const state = {
        strategyOptions,
        request: strategyOptions.request ||
            request.defaults({
                baseUrl: "https://api.github.com",
                headers: {
                    "user-agent": `octokit-auth-basic.js/${VERSION} ${getUserAgent()}`,
                },
            }),
    };
    return Object.assign(auth.bind(null, state), {
        hook: hook.bind(null, state),
    });
}
Example #13
Source File: index.js    From change-string-case-action with ISC License 6 votes vote down vote up
constructor(request, response) {
        const message = response.data.errors[0].message;
        super(message);
        Object.assign(this, response.data);
        Object.assign(this, { headers: response.headers });
        this.name = "GraphqlError";
        this.request = request;
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
Example #14
Source File: index.js    From zcl-eth-key-converter with MIT License 6 votes vote down vote up
async function getToken(state, authOptions, request) {
    if (state.token && !authOptions.refresh) {
        return state.token;
    }
    const basicAuthorization = `basic ${btoa(`${state.strategyOptions.username}:${state.strategyOptions.password}`)}`;
    const timestamp = new Date().toISOString().substr(0, 10);
    const fingerprintDefault = state.strategyOptions.token.note
        ? undefined
        : Math.random().toString(36).substr(2);
    const fingerprint = state.strategyOptions.token.fingerprint || fingerprintDefault;
    const note = state.strategyOptions.token.note || `octokit ${timestamp} ${fingerprint}`;
    const scopes = state.strategyOptions.token.scopes || [];
    const noteUrl = state.strategyOptions.token.noteUrl ||
        "https://github.com/octokit/auth-basic.js#readme";
    const options = Object.assign({
        method: "POST",
        url: "/authorizations",
        headers: {
            authorization: basicAuthorization,
        },
        note,
        note_url: noteUrl,
        scopes,
    }, fingerprint ? { fingerprint } : null, state.strategyOptions.token.clientId
        ? {
            client_id: state.strategyOptions.token.clientId,
            client_secret: state.strategyOptions.token.clientSecret,
        }
        : null);
    const { data: { id, token }, } = await requestWith2Fa(state, options, request);
    state.token = {
        type: "token",
        tokenType: "oauth",
        id,
        token,
        username: state.strategyOptions.username,
    };
    return state.token;
}
Example #15
Source File: index.js    From payload-info-action with MIT License 6 votes vote down vote up
constructor(request, response) {
        const message = response.data.errors[0].message;
        super(message);
        Object.assign(this, response.data);
        this.name = "GraphqlError";
        this.request = request;
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
Example #16
Source File: index.js    From dotnet-bump-version with MIT License 6 votes vote down vote up
function graphql(request, query, options) {
    if (typeof query === "string" && options && "query" in options) {
        return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
    }
    const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
    const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
        if (NON_VARIABLE_OPTIONS.includes(key)) {
            result[key] = parsedOptions[key];
            return result;
        }
        if (!result.variables) {
            result.variables = {};
        }
        result.variables[key] = parsedOptions[key];
        return result;
    }, {});
    // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
    // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
    const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
    if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
        requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
    }
    return request(requestOptions).then((response) => {
        if (response.data.errors) {
            const headers = {};
            for (const key of Object.keys(response.headers)) {
                headers[key] = response.headers[key];
            }
            throw new GraphqlError(requestOptions, {
                headers,
                data: response.data,
            });
        }
        return response.data.data;
    });
}
Example #17
Source File: index.js    From payload-info-action with MIT License 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint
    });
}
Example #18
Source File: index.js    From zcl-eth-key-converter with MIT License 6 votes vote down vote up
createBasicAuth = function createBasicAuth(options) {
    console.warn(`[@octokit/auth-basic] Basic authentication has been deprecated. See https://github.com/octokit/auth-basic.js/#deprecation`);
    ["username", "password", "on2Fa"].forEach((option) => {
        if (!options.hasOwnProperty(option)) {
            throw new Error(`[@octokit/auth-basic] ${option} option is required`);
        }
    });
    const strategyOptions = Object.assign({
        token: {},
    }, options);
    const state = {
        strategyOptions,
        request: strategyOptions.request ||
            request.defaults({
                baseUrl: "https://api.github.com",
                headers: {
                    "user-agent": `octokit-auth-basic.js/${VERSION} ${getUserAgent()}`,
                },
            }),
    };
    return Object.assign(auth.bind(null, state), {
        hook: hook.bind(null, state),
    });
}
Example #19
Source File: index.js    From verify-linked-issue-action with MIT License 6 votes vote down vote up
function withDefaults(request$1, newDefaults) {
    const newRequest = request$1.defaults(newDefaults);
    const newApi = (query, options) => {
        return graphql(newRequest, query, options);
    };
    return Object.assign(newApi, {
        defaults: withDefaults.bind(null, newRequest),
        endpoint: request.endpoint,
    });
}
Example #20
Source File: index.js    From dotnet-bump-version with MIT License 6 votes vote down vote up
constructor(request, response) {
        const message = response.data.errors[0].message;
        super(message);
        Object.assign(this, response.data);
        Object.assign(this, { headers: response.headers });
        this.name = "GraphqlError";
        this.request = request;
        // Maintains proper stack trace (only available on V8)
        /* istanbul ignore next */
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, this.constructor);
        }
    }
Example #21
Source File: index.js    From compute-tag with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
graphql$1 = withDefaults(request, {
    headers: {
        "user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
    },
    method: "POST",
    url: "/graphql",
})
Example #22
Source File: index.js    From zcl-eth-key-converter with MIT License 5 votes vote down vote up
async function requestWith2Fa(state, options, customRequest) {
    const request = customRequest || state.request;
    try {
        if (state.totp) {
            options = Object.assign({}, options, {
                headers: Object.assign({}, options.headers, {
                    "x-github-otp": state.totp,
                }),
            });
        }
        const response = await request(options);
        return response;
    }
    catch (error) {
        if (!error.headers)
            throw error;
        const totpRequired = /required/.test(error.headers["x-github-otp"] || "");
        const hasSmsDelivery = /sms/.test(error.headers["x-github-otp"] || "");
        // handle "2FA required" error only
        if (error.status !== 401 || !totpRequired) {
            throw error;
        }
        if (error.status === 401 &&
            totpRequired &&
            error.request.headers["x-github-otp"]) {
            if (state.totp) {
                // TOTP is no longer valid, request again
                delete state.totp;
            }
            else {
                throw new RequestError("Invalid TOTP (time-based one-time password) for two-factor authentication", 401, {
                    headers: error.headers,
                    request: error.request,
                });
            }
        }
        // If user has 2Fa with SMS configured, send a bogus "PATCH /authorizations"
        // request to trigger the TOTP delivery via SMS, unless the current request
        // already triggered a delivery
        if (hasSmsDelivery && !isSmsTriggeringRoute(options)) {
            try {
                await request("PATCH /authorizations", {
                    headers: options.headers,
                });
            }
            catch (error) {
                // we expect a 401
                if (error.status !== 401)
                    throw error;
            }
        }
        // we set state.totp after the request to make sure that it's valid
        const totp = await state.strategyOptions.on2Fa();
        try {
            const response = await requestWith2Fa(state, Object.assign({}, options, {
                headers: Object.assign({}, options.headers, {
                    "x-github-otp": totp,
                }),
            }), customRequest);
            state.totp = totp;
            return response;
        }
        catch (error) {
            // error without a headers property is an unexpected error
            // which we don’t cover with tests
            /* istanbul ignore next */
            if (!error.headers)
                throw error;
            const totpRequired = /required/.test(error.headers["x-github-otp"] || "");
            // unless the error is an invalid TOTP, we can cache it
            if (!totpRequired) {
                state.totp = totp;
            }
            throw error;
        }
    }
}
Example #23
Source File: index.js    From compute-tag with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
function graphql(request, query, options) {
    if (options) {
        if (typeof query === "string" && "query" in options) {
            return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
        }
        for (const key in options) {
            if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
                continue;
            return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
        }
    }
    const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
    const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
        if (NON_VARIABLE_OPTIONS.includes(key)) {
            result[key] = parsedOptions[key];
            return result;
        }
        if (!result.variables) {
            result.variables = {};
        }
        result.variables[key] = parsedOptions[key];
        return result;
    }, {});
    // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
    // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
    const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
    if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
        requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
    }
    return request(requestOptions).then((response) => {
        if (response.data.errors) {
            const headers = {};
            for (const key of Object.keys(response.headers)) {
                headers[key] = response.headers[key];
            }
            throw new GraphqlError(requestOptions, {
                headers,
                data: response.data,
            });
        }
        return response.data.data;
    });
}
Example #24
Source File: index.js    From verify-linked-issue-action with MIT License 5 votes vote down vote up
graphql$1 = withDefaults(request, {
    headers: {
        "user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
    },
    method: "POST",
    url: "/graphql",
})
Example #25
Source File: index.js    From deploy-gae-action with MIT License 5 votes vote down vote up
graphql$1 = withDefaults(request, {
    headers: {
        "user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
    },
    method: "POST",
    url: "/graphql",
})
Example #26
Source File: index.js    From verify-linked-issue-action with MIT License 5 votes vote down vote up
graphql = withDefaults(request, {
    headers: {
        "user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`,
    },
    method: "POST",
    url: "/graphql",
})
Example #27
Source File: index.js    From change-string-case-action with ISC License 5 votes vote down vote up
constructor(options = {}) {
        const hook = new Collection();
        const requestDefaults = {
            baseUrl: request.endpoint.DEFAULTS.baseUrl,
            headers: {},
            request: Object.assign({}, options.request, {
                hook: hook.bind(null, "request"),
            }),
            mediaType: {
                previews: [],
                format: "",
            },
        };
        // prepend default user agent with `options.userAgent` if set
        requestDefaults.headers["user-agent"] = [
            options.userAgent,
            `octokit-core.js/${VERSION} ${getUserAgent()}`,
        ]
            .filter(Boolean)
            .join(" ");
        if (options.baseUrl) {
            requestDefaults.baseUrl = options.baseUrl;
        }
        if (options.previews) {
            requestDefaults.mediaType.previews = options.previews;
        }
        if (options.timeZone) {
            requestDefaults.headers["time-zone"] = options.timeZone;
        }
        this.request = request.defaults(requestDefaults);
        this.graphql = withCustomRequest(this.request).defaults({
            ...requestDefaults,
            baseUrl: requestDefaults.baseUrl.replace(/\/api\/v3$/, "/api"),
        });
        this.log = Object.assign({
            debug: () => { },
            info: () => { },
            warn: console.warn.bind(console),
            error: console.error.bind(console),
        }, options.log);
        this.hook = hook;
        // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
        //     is unauthenticated. The `this.auth()` method is a no-op and no request hook is registred.
        // (2) If only `options.auth` is set, use the default token authentication strategy.
        // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
        // TODO: type `options.auth` based on `options.authStrategy`.
        if (!options.authStrategy) {
            if (!options.auth) {
                // (1)
                this.auth = async () => ({
                    type: "unauthenticated",
                });
            }
            else {
                // (2)
                const auth = createTokenAuth(options.auth);
                // @ts-ignore  ¯\_(ツ)_/¯
                hook.wrap("request", auth.hook);
                this.auth = auth;
            }
        }
        else {
            const auth = options.authStrategy(Object.assign({
                request: this.request,
            }, options.auth));
            // @ts-ignore  ¯\_(ツ)_/¯
            hook.wrap("request", auth.hook);
            this.auth = auth;
        }
        // apply plugins
        // https://stackoverflow.com/a/16345172
        const classConstructor = this.constructor;
        classConstructor.plugins.forEach((plugin) => {
            Object.assign(this, plugin(this, options));
        });
    }
Example #28
Source File: index.js    From verify-linked-issue-action with MIT License 5 votes vote down vote up
function graphql(request, query, options) {
    if (options) {
        if (typeof query === "string" && "query" in options) {
            return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`));
        }
        for (const key in options) {
            if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
                continue;
            return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`));
        }
    }
    const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
    const requestOptions = Object.keys(parsedOptions).reduce((result, key) => {
        if (NON_VARIABLE_OPTIONS.includes(key)) {
            result[key] = parsedOptions[key];
            return result;
        }
        if (!result.variables) {
            result.variables = {};
        }
        result.variables[key] = parsedOptions[key];
        return result;
    }, {});
    // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix
    // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451
    const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl;
    if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
        requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
    }
    return request(requestOptions).then((response) => {
        if (response.data.errors) {
            const headers = {};
            for (const key of Object.keys(response.headers)) {
                headers[key] = response.headers[key];
            }
            throw new GraphqlResponseError(requestOptions, headers, response.data);
        }
        return response.data.data;
    });
}
Example #29
Source File: index.js    From deploy-gae-action with MIT License 5 votes vote down vote up
constructor(options = {}) {
        const hook = new Collection();
        const requestDefaults = {
            baseUrl: request.endpoint.DEFAULTS.baseUrl,
            headers: {},
            request: Object.assign({}, options.request, {
                hook: hook.bind(null, "request"),
            }),
            mediaType: {
                previews: [],
                format: "",
            },
        };
        // prepend default user agent with `options.userAgent` if set
        requestDefaults.headers["user-agent"] = [
            options.userAgent,
            `octokit-core.js/${VERSION} ${getUserAgent()}`,
        ]
            .filter(Boolean)
            .join(" ");
        if (options.baseUrl) {
            requestDefaults.baseUrl = options.baseUrl;
        }
        if (options.previews) {
            requestDefaults.mediaType.previews = options.previews;
        }
        if (options.timeZone) {
            requestDefaults.headers["time-zone"] = options.timeZone;
        }
        this.request = request.defaults(requestDefaults);
        this.graphql = withCustomRequest(this.request).defaults({
            ...requestDefaults,
            baseUrl: requestDefaults.baseUrl.replace(/\/api\/v3$/, "/api"),
        });
        this.log = Object.assign({
            debug: () => { },
            info: () => { },
            warn: console.warn.bind(console),
            error: console.error.bind(console),
        }, options.log);
        this.hook = hook;
        // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance
        //     is unauthenticated. The `this.auth()` method is a no-op and no request hook is registred.
        // (2) If only `options.auth` is set, use the default token authentication strategy.
        // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance.
        // TODO: type `options.auth` based on `options.authStrategy`.
        if (!options.authStrategy) {
            if (!options.auth) {
                // (1)
                this.auth = async () => ({
                    type: "unauthenticated",
                });
            }
            else {
                // (2)
                const auth = createTokenAuth(options.auth);
                // @ts-ignore  ¯\_(ツ)_/¯
                hook.wrap("request", auth.hook);
                this.auth = auth;
            }
        }
        else {
            const auth = options.authStrategy(Object.assign({
                request: this.request,
            }, options.auth));
            // @ts-ignore  ¯\_(ツ)_/¯
            hook.wrap("request", auth.hook);
            this.auth = auth;
        }
        // apply plugins
        // https://stackoverflow.com/a/16345172
        const classConstructor = this.constructor;
        classConstructor.plugins.forEach((plugin) => {
            Object.assign(this, plugin(this, options));
        });
    }