UNPKG

3.12 kBJavaScriptView Raw
1"use strict";
2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4 return new (P || (P = Promise))(function (resolve, reject) {
5 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8 step((generator = generator.apply(thisArg, _arguments || [])).next());
9 });
10};
11Object.defineProperty(exports, "__esModule", { value: true });
12class XKCDAPI {
13 constructor(apiClient, options) {
14 this.apiClient = apiClient;
15 this.options = options;
16 this.lowestIndex = 1;
17 this.JSON_INFO_FILE = 'info.0.json';
18 }
19 getByIndex(index, options = {}) {
20 return __awaiter(this, void 0, void 0, function* () {
21 if (index < this.lowestIndex) {
22 throw new Error(`Index is lower than the lowest index of ${this.lowestIndex}.`);
23 }
24 const { data: metaData } = yield this.apiClient.get(`/${index}/${this.JSON_INFO_FILE}`);
25 if (options.withData === true) {
26 const imageData = yield this.getImage(metaData.img);
27 return Object.assign(Object.assign({}, metaData), { data: imageData });
28 }
29 return metaData;
30 });
31 }
32 getLatest(options = {}) {
33 return __awaiter(this, void 0, void 0, function* () {
34 const { data: metaData } = yield this.apiClient.get(`/${this.JSON_INFO_FILE}`);
35 if (options.withData) {
36 const imageData = yield this.getImage(metaData.img);
37 return Object.assign(Object.assign({}, metaData), { data: imageData });
38 }
39 return metaData;
40 });
41 }
42 getRandom(options = {}) {
43 return __awaiter(this, void 0, void 0, function* () {
44 const latest = yield this.getLatest();
45 const randomIndex = Math.floor(Math.random() * (latest.num - this.lowestIndex + 1)) + this.lowestIndex;
46 const metaData = yield this.getByIndex(randomIndex);
47 if (options.withData === true) {
48 const imageData = yield this.getImage(metaData.img);
49 return Object.assign(Object.assign({}, metaData), { data: imageData });
50 }
51 return metaData;
52 });
53 }
54 getImage(imageUrl) {
55 return __awaiter(this, void 0, void 0, function* () {
56 const { data, headers } = yield this.apiClient.request({
57 responseType: 'arraybuffer',
58 url: imageUrl,
59 });
60 const contentType = headers['content-type'];
61 return {
62 data,
63 mimeType: contentType ? String(contentType) : undefined,
64 };
65 });
66 }
67}
68exports.XKCDAPI = XKCDAPI;
69//# sourceMappingURL=XKCDAPI.js.map
\No newline at end of file