UNPKG

twitch-js

Version:

Javascript library for the Twitch Messaging Interface.

335 lines 14.1 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); var includes_1 = __importDefault(require("lodash/includes")); var toLower_1 = __importDefault(require("lodash/toLower")); var toUpper_1 = __importDefault(require("lodash/toUpper")); var twitch_1 = require("../twitch"); var logger_1 = __importDefault(require("../utils/logger")); var fetch_1 = __importDefault(require("../utils/fetch")); var Errors = __importStar(require("../utils/fetch/Errors")); var validators = __importStar(require("./utils/validators")); var types_1 = require("./types"); var invariant_1 = __importDefault(require("invariant")); var isEmpty_1 = __importDefault(require("lodash/isEmpty")); __export(require("./types")); /** * Make requests to Twitch API. * * ## Initializing * * ```js * // With a token ... * const token = 'cfabdegwdoklmawdzdo98xt2fo512y' * const { api } = new TwitchJs({ token }) * * // ... or with a client ID ... * const clientId = 'uo6dggojyb8d6soh92zknwmi5ej1q2' * const { api } = new TwitchJs({ clientId }) * ``` * * **Note:** The recommended way to initialize the API client is with a token. * * ## Making requests * * By default, the API client makes requests to the * [Helix API](https://dev.twitch.tv/docs/api), and exposes [[Api.get]], * [[Api.post]] and [[Api.put]] methods. Query string parameters and body * parameters are provided via `options.search` and `options.body` properties, * respectively. * * To make requests to the [Kraken/v5 API](https://dev.twitch.tv/docs/v5), use * `options.version = 'kraken'` * * ### Examples * * #### Get bits leaderboard * ```js * api * .get('bits/leaderboard', { search: { user_id: '44322889' } }) * .then(response => { * // Do stuff with response ... * }) * ``` * * #### Get the latest Overwatch live streams * ``` * api * .get('streams', { version: 'kraken', search: { game: 'Overwatch' } }) * .then(response => { * // Do stuff with response ... * }) * ``` * * #### Start a channel commercial * ``` * const channelId = '44322889' * api * .post(`channels/${channelId}/commercial`, { * version: 'kraken', * body: { length: 30 }, * }) * .then(response => { * // Do stuff with response ... * }) * ``` */ var Api = /** @class */ (function () { function Api(maybeOptions) { if (maybeOptions === void 0) { maybeOptions = {}; } this._readyState = types_1.ApiReadyStates.READY; this.options = maybeOptions; this._log = logger_1.default(__assign({ name: 'Api' }, this.options.log)); } Object.defineProperty(Api.prototype, "options", { get: function () { return this._options; }, set: function (maybeOptions) { this._options = validators.apiOptions(maybeOptions); }, enumerable: true, configurable: true }); Object.defineProperty(Api.prototype, "readyState", { get: function () { return this._readyState; }, enumerable: true, configurable: true }); Object.defineProperty(Api.prototype, "status", { get: function () { return this._status; }, enumerable: true, configurable: true }); /** * New client options. To update `token` or `clientId`, use [**api.initialize()**]{@link Api#initialize}. */ Api.prototype.updateOptions = function (options) { var _a = this.options, clientId = _a.clientId, token = _a.token; this.options = __assign(__assign({}, options), { clientId: clientId, token: token }); }; /** * Initialize API client and retrieve status. * @see https://dev.twitch.tv/docs/v5/#root-url */ Api.prototype.initialize = function (newOptions) { return __awaiter(this, void 0, void 0, function () { var statusResponse; return __generator(this, function (_a) { switch (_a.label) { case 0: if (newOptions) { this.options = __assign(__assign({}, this.options), newOptions); } if (!newOptions && this.readyState === 2) { return [2 /*return*/, Promise.resolve()]; } return [4 /*yield*/, this.get('', { version: twitch_1.ApiVersions.Kraken, })]; case 1: statusResponse = _a.sent(); this._readyState = types_1.ApiReadyStates.INITIALIZED; this._status = statusResponse; return [2 /*return*/, statusResponse]; } }); }); }; /** * Check if current credentials include `scope`. * @see https://dev.twitch.tv/docs/authentication/#twitch-api-v5 */ Api.prototype.hasScope = function ( /** Scope to check */ scope) { var _this = this; return new Promise(function (resolve, reject) { if (_this.readyState !== 2 || !_this.status) { return reject(false); } return includes_1.default(_this.status.token.authorization.scopes, scope) ? resolve(true) : reject(false); }); }; /** * GET endpoint. * * @example <caption>Get Live Overwatch Streams (Kraken)</caption> * ``` * api.get('streams', { version: 'kraken', search: { game: 'Overwatch' } }) * .then(response => { * // Do stuff with response ... * }) * ``` * * @example <caption>Get user follows (Helix)</caption> * ``` * api.get('users/follows', { search: { to_id: '23161357' } }) * .then(response => { * // Do stuff with response ... * }) * ``` */ Api.prototype.get = function (endpoint, options) { if (endpoint === void 0) { endpoint = ''; } return this._handleFetch(endpoint, options); }; /** * POST endpoint. */ Api.prototype.post = function (endpoint, options) { return this._handleFetch(endpoint, __assign(__assign({}, options), { method: 'post' })); }; /** * PUT endpoint. */ Api.prototype.put = function (endpoint, options) { return this._handleFetch(endpoint, __assign(__assign({}, options), { method: 'put' })); }; Api.prototype._isVersionHelix = function (version) { return toLower_1.default(version) === twitch_1.ApiVersions.Helix; }; Api.prototype._getBaseUrl = function (version) { return types_1.Settings[version].baseUrl; }; Api.prototype._getHeaders = function (version) { var _a = this.options, clientId = _a.clientId, token = _a.token; var isHelix = this._isVersionHelix(version); invariant_1.default(isHelix ? !(isEmpty_1.default(clientId) && isEmpty_1.default(token)) : true, '[twitch-js/Api] To call a Helix endpoint, a `clientId` or `token` must be provided'); var headers = isHelix ? { 'Client-ID': clientId } : { Accept: 'application/vnd.twitchtv.v5+json', 'Client-ID': clientId }; if (token) { var authorizationHeader = types_1.Settings[version].authorizationHeader; var authorization = authorizationHeader + " " + token; return __assign(__assign({}, headers), { Authorization: authorization }); } return headers; }; Api.prototype._handleFetch = function (maybeUrl, options) { if (maybeUrl === void 0) { maybeUrl = ''; } if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var _a, version, fetchOptions, baseUrl, url, message, fetchProfiler, performRequest, error_1, token; var _this = this; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = options.version, version = _a === void 0 ? twitch_1.ApiVersions.Helix : _a, fetchOptions = __rest(options, ["version"]); baseUrl = this._getBaseUrl(version); url = baseUrl + "/" + maybeUrl; message = (toUpper_1.default(fetchOptions.method) || 'GET') + " " + url; fetchProfiler = this._log.profile(); performRequest = function () { return fetch_1.default(url, __assign(__assign({}, fetchOptions), { headers: __assign(__assign({}, fetchOptions.headers), _this._getHeaders(version)) })); }; _b.label = 1; case 1: _b.trys.push([1, 3, 9, 10]); return [4 /*yield*/, performRequest()]; case 2: return [2 /*return*/, _b.sent()]; case 3: error_1 = _b.sent(); if (!(error_1 instanceof Errors.AuthenticationError)) return [3 /*break*/, 8]; return [4 /*yield*/, this.options.onAuthenticationFailure()]; case 4: token = _b.sent(); if (!token) return [3 /*break*/, 6]; return [4 /*yield*/, this.initialize({ token: token })]; case 5: _b.sent(); this._log.info(message + " ... re-initializing with new token"); _b.label = 6; case 6: this._log.info(message + " ... retrying"); return [4 /*yield*/, performRequest()]; case 7: return [2 /*return*/, _b.sent()]; case 8: throw new Errors.FetchError(error_1, message); case 9: fetchProfiler.done(message); return [7 /*endfinally*/]; case 10: return [2 /*return*/]; } }); }); }; return Api; }()); exports.default = Api; //# sourceMappingURL=index.js.map