UNPKG

@ffflorian/xkcdjs

Version:
69 lines (68 loc) 3.11 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.XKCDAPI = void 0; class XKCDAPI { constructor(apiClient, options) { this.apiClient = apiClient; this.options = options; this.lowestIndex = 1; this.JSON_INFO_FILE = 'info.0.json'; } getByIndex(index_1) { return __awaiter(this, arguments, void 0, function* (index, options = {}) { if (index < this.lowestIndex) { throw new Error(`Index is lower than the lowest index of ${this.lowestIndex}.`); } const { data: metaData } = yield this.apiClient.get(`/${index}/${this.JSON_INFO_FILE}`); if (options.withData === true) { const imageData = yield this.getImage(metaData.img); return Object.assign(Object.assign({}, metaData), { data: imageData }); } return metaData; }); } getLatest() { return __awaiter(this, arguments, void 0, function* (options = {}) { const { data: metaData } = yield this.apiClient.get(`/${this.JSON_INFO_FILE}`); if (options.withData) { const imageData = yield this.getImage(metaData.img); return Object.assign(Object.assign({}, metaData), { data: imageData }); } return metaData; }); } getRandom() { return __awaiter(this, arguments, void 0, function* (options = {}) { const latest = yield this.getLatest(); const randomIndex = Math.floor(Math.random() * (latest.num - this.lowestIndex + 1)) + this.lowestIndex; const metaData = yield this.getByIndex(randomIndex); if (options.withData === true) { const imageData = yield this.getImage(metaData.img); return Object.assign(Object.assign({}, metaData), { data: imageData }); } return metaData; }); } getImage(imageUrl) { return __awaiter(this, void 0, void 0, function* () { const { data, headers } = yield this.apiClient.get(imageUrl, { responseType: 'arraybuffer', }); const contentType = headers.get('content-type'); return { data, mimeType: contentType ? String(contentType) : undefined, }; }); } } exports.XKCDAPI = XKCDAPI;