UNPKG

twitch-js

Version:

Javascript library for the Twitch Messaging Interface.

377 lines 16 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; 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; }; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; 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 = __importStar(require("../utils/fetch")); var validators = __importStar(require("./utils/validators")); var types_1 = 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(options) { this._readyState = types_1.ApiReadyStates.READY; this._options = validators.apiOptions(options); this._log = logger_1.default(__assign({ name: 'Api' }, this._options.log)); } Object.defineProperty(Api.prototype, "readyState", { get: function () { return this._readyState; }, enumerable: false, configurable: true }); Object.defineProperty(Api.prototype, "status", { get: function () { return this._status; }, enumerable: false, 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 = validators.apiOptions(__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 = validators.apiOptions(__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(); if ('token' in statusResponse) { 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); var headers = {}; if (!isHelix) { headers['Accept'] = 'application/vnd.twitchtv.v5+json'; } if (clientId) { headers['Client-ID'] = clientId; } if (token) { headers['Authorization'] = types_1.Settings[version].authorizationHeader + " " + token; } 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, headers, optionHeaders, optionHeaders_1, optionHeaders_1_1, _b, name_1, value, performRequest, caughtError, error_1, token; var e_1, _c; return __generator(this, function (_d) { switch (_d.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(); headers = this._getHeaders(version); optionHeaders = Object.entries(fetchOptions.headers || {}); try { for (optionHeaders_1 = __values(optionHeaders), optionHeaders_1_1 = optionHeaders_1.next(); !optionHeaders_1_1.done; optionHeaders_1_1 = optionHeaders_1.next()) { _b = __read(optionHeaders_1_1.value, 2), name_1 = _b[0], value = _b[1]; headers[String(name_1)] = value; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (optionHeaders_1_1 && !optionHeaders_1_1.done && (_c = optionHeaders_1.return)) _c.call(optionHeaders_1); } finally { if (e_1) throw e_1.error; } } performRequest = function () { return fetch_1.default(url, __assign(__assign({}, fetchOptions), { headers: headers })); }; _d.label = 1; case 1: _d.trys.push([1, 3, 9, 10]); return [4 /*yield*/, performRequest()]; case 2: return [2 /*return*/, _d.sent()]; case 3: error_1 = _d.sent(); caughtError = error_1; if (!(typeof this._options.onAuthenticationFailure === 'function' && error_1 instanceof fetch_1.FetchError && error_1.status === 401)) return [3 /*break*/, 8]; return [4 /*yield*/, this._options.onAuthenticationFailure()]; case 4: token = _d.sent(); if (!token) return [3 /*break*/, 6]; return [4 /*yield*/, this.initialize({ token: token })]; case 5: _d.sent(); this._log.info(message + " ... re-initializing with new token"); _d.label = 6; case 6: this._log.info(message + " ... retrying"); return [4 /*yield*/, performRequest()]; case 7: return [2 /*return*/, _d.sent()]; case 8: throw error_1; case 9: fetchProfiler.done(message, caughtError); return [7 /*endfinally*/]; case 10: return [2 /*return*/]; } }); }); }; return Api; }()); exports.default = Api; //# sourceMappingURL=Api.js.map