twitch-comment-downloader
Version:
Fetch comments for a given twitch vod
86 lines • 2.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = require("axios");
const constants_1 = require("./constants");
/**
* Responsible for handling interaction with Twitch comment APIs
*
* @export
* @class TwitchCommentDownloader
*/
class TwitchCommentDownloader {
constructor(clientId) {
if (!clientId) {
throw new Error("constructor requires client id parameter");
}
this.clientId = clientId;
}
/**
* Returns all comments for a given vod id
*
* @param {string} vodId
* @returns {Promise<ITwitchComment[]>}
*/
async getComments(vodId) {
const allComments = [];
let cursor;
do {
const commentsMaybe = await this.getCommentsChunk(vodId, cursor);
if (!commentsMaybe.success) {
throw new Error(commentsMaybe.reason);
}
const { comments, _next } = commentsMaybe.result;
allComments.push(...comments);
cursor = _next;
} while (cursor);
return allComments;
}
;
/**
* Get comments for a given vod
*
* @static
* @param {string} vodId
* @param {string} [cursor]
* @returns {Promise<Result<ITwitchCommentResponse>>}
*/
async getCommentsChunk(vodId, cursor) {
const url = cursor
? `${constants_1.default.TWITCH_API_BASE}/videos/${vodId}/comments?cursor=${cursor}`
: `${constants_1.default.TWITCH_API_BASE}/videos/${vodId}/comments?content_offset_seconds=0`;
const method = "GET";
const headers = {
"client-id": this.clientId,
"content-type": "application/json; charset=UTF-8",
"accept": "application/vnd.twitchtv.v5+json; charset=UTF-8",
"accept-encoding": "gzip, deflate, br"
};
const config = {
url,
headers,
method
};
let response;
try {
response = await axios_1.default(config);
}
catch (error) {
console.error(`[TWITCH] [GET-COMMENTS] request failed: ${error.message}`);
if (error.response && error.response.data) {
console.error("[TWITCH] [GET-COMMENTS] error response payload", error.response.data);
}
return {
success: false,
reason: error
};
}
const payload = response.data;
return {
success: true,
result: payload
};
}
;
}
exports.TwitchCommentDownloader = TwitchCommentDownloader;
//# sourceMappingURL=comments.js.map