Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: Elitezen/open-trivia-db-wrapper
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 2.1.5
Choose a base ref
...
head repository: Elitezen/open-trivia-db-wrapper
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: main
Choose a head ref
  • 5 commits
  • 37 files changed
  • 2 contributors

Commits on Mar 25, 2023

  1. Further documented typings and functions

    Elitezen committed Mar 25, 2023
    Copy the full SHA
    a12e4ca View commit details

Commits on Mar 26, 2024

  1. Copy the full SHA
    b1ffbee View commit details

Commits on May 30, 2024

  1. Readded /dist to .gitignore

    Elitezen committed May 30, 2024
    Copy the full SHA
    8d10225 View commit details
  2. Updated README

    Elitezen committed May 30, 2024
    Copy the full SHA
    6d7723e View commit details

Commits on Jun 5, 2024

  1. Corrected Typos in README

    Elitezen committed Jun 5, 2024
    Copy the full SHA
    a357f16 View commit details
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/node_modules
/bin
/dist
dist/
.DS_Store
*.tgz
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

# 2.1.6
- Added typescript as a developer depencency.
- Added safegaurd for unknown thrown exceptions from `OpenTDBError`.

# 2.1.5
- Fixed the issue of the dist/ folder not being included.

30 changes: 15 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -7,21 +7,19 @@

`open-trivia-db` is a small and simple library for interacting with the [OpenTDB](https://opentdb.com/) API.

**Live Demo**: https://replit.com/@Elitezenv/open-trivia-db-DEMO?v=1

**Documentation**: https://github.com/Elitezen/open-trivia-db-wrapper/wiki/Documentation

## Discord.JS Add On

Planning a trivia command for your Discord bot?
`discord-trivia` v2 is coming!: https://github.com/Elitezen/discord-trivia
Checkout the powerful module `discord-trivia`: https://github.com/Elitezen/discord-trivia

# 2.1.5
- Fixed the issue of the dist/ folder not being included.
# 2.1.6
- Added typescript as a developer depencency.
- Added safegaurd for unknown thrown exceptions from `OpenTDBError`.

## Example Code
```js
import { getQuestions, CategoryNames } from "open-trivia-db";
import { getQuestions, CategoryNames, QuestionDifficulties } from "open-trivia-db";

const questions = await getQuestions({
amount: 10,
@@ -89,18 +87,20 @@ To jump between resolvables, use `Category.idByName()` and `Category.nameById()`
```js
import { Category, CategoryNames } from "open-trivia-db";

Category.idByName('Art'); // 25
Category.nameById(25); // 'Art'
Category.idByName('Art'); // 25
Category.idByName(CategoryNames.Art); // 25

Category.nameById(25); // 'Art'
```

### Getting a Category's Data
Use `Category.getCategory()` to get a category's data such as name, id, and question counts.

```js
import { Category, CategoryNames } from "open-trivia-db"
import { Category, CategoryNames } from "open-trivia-db";

Category.getCategory(CategoryNames.Geography)
.then(console.log)
.then(console.log);
```

```js
@@ -117,18 +117,18 @@ Category.getCategory(CategoryNames.Geography)
You can also complete a category's data through a question via `Question.category.getData()`

```js
const targetQuestion = questions[0] // from getQuestions()
const targetQuestion = questions[0]; // from getQuestions()

targetQuestion.category.getData()
.then(console.log)
.then(console.log);
```

## Sessions
A session ensures you are not supplied a question more than once throughout it's lifetime.

Initialize a session and supply the instance into `getQuestions()`. Make sure to await or resolve `Session.start()`.
```js
import { Session } from "open-trivia-db"
import { Session } from "open-trivia-db";

const mySession = new Session();
await mySession.start();
@@ -138,7 +138,7 @@ getQuestions({
})
```

`getQuestions()` will return an error once your session has served every single question in OpenTDB. Don't worry, theres thousands of questions! You will likely never come accross a session's end. However, if you wish to reset your session, use `Session.reset()`.
`getQuestions()` will return an error once your session has served every single question in OpenTDB. Don't worry, there are thousands of questions! You will likely never come accross a session's end. However, if you wish to reset your session, use `Session.reset()`.

```js
await mySession.reset();
11 changes: 11 additions & 0 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Category from "./src/Classes/Category";
import Constructor from "./src/Classes/Constructor";
import OpenTDBError from "./src/Classes/OpenTDBError";
import Session from "./src/Classes/Session";
import Util from "./src/Classes/Util";
import getCategory from "./src/Functions/getCategory";
import getQuestions from "./src/Functions/getQuestions";
import { CategoryNames, QuestionDifficulties, QuestionEncodings, QuestionTypes, Routes } from "./src/Typings/enums";
import type { CategoryData, ErrorResponse, MinifiedCategoryData, Question, QuestionOptions, RawQuestion, RawCategoryResponse, RawQuestionResponse, RawSessionStartResponse } from "./src/Typings/interfaces";
import type { AllAnswers, BooleanString, CategoryNameType, CategoryResolvable, Dictionary, ErrorCode, IncorrectAnswers, QuestionDifficultyType, QuestionEncodingType, QuestionTypeType, ResponseCode, SimpleDictionary, ExtendedDictionary } from "./src/Typings/types";
export { Category, Constructor, OpenTDBError, Session, Util, getCategory, getQuestions, CategoryNames, QuestionDifficulties, QuestionEncodings, QuestionTypes, Routes, CategoryData, ErrorResponse, MinifiedCategoryData, Question, QuestionOptions, RawQuestion, RawCategoryResponse, RawQuestionResponse, RawSessionStartResponse, AllAnswers, BooleanString, CategoryNameType, CategoryResolvable, Dictionary, ErrorCode, IncorrectAnswers, QuestionDifficultyType, QuestionEncodingType, QuestionTypeType, ResponseCode, SimpleDictionary, ExtendedDictionary, };
23 changes: 23 additions & 0 deletions dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Routes = exports.QuestionTypes = exports.QuestionEncodings = exports.QuestionDifficulties = exports.CategoryNames = exports.getQuestions = exports.getCategory = exports.Util = exports.Session = exports.OpenTDBError = exports.Constructor = exports.Category = void 0;
var Category_1 = require("./src/Classes/Category");
exports.Category = Category_1.default;
var Constructor_1 = require("./src/Classes/Constructor");
exports.Constructor = Constructor_1.default;
var OpenTDBError_1 = require("./src/Classes/OpenTDBError");
exports.OpenTDBError = OpenTDBError_1.default;
var Session_1 = require("./src/Classes/Session");
exports.Session = Session_1.default;
var Util_1 = require("./src/Classes/Util");
exports.Util = Util_1.default;
var getCategory_1 = require("./src/Functions/getCategory");
exports.getCategory = getCategory_1.default;
var getQuestions_1 = require("./src/Functions/getQuestions");
exports.getQuestions = getQuestions_1.default;
var enums_1 = require("./src/Typings/enums");
Object.defineProperty(exports, "CategoryNames", { enumerable: true, get: function () { return enums_1.CategoryNames; } });
Object.defineProperty(exports, "QuestionDifficulties", { enumerable: true, get: function () { return enums_1.QuestionDifficulties; } });
Object.defineProperty(exports, "QuestionEncodings", { enumerable: true, get: function () { return enums_1.QuestionEncodings; } });
Object.defineProperty(exports, "QuestionTypes", { enumerable: true, get: function () { return enums_1.QuestionTypes; } });
Object.defineProperty(exports, "Routes", { enumerable: true, get: function () { return enums_1.Routes; } });
42 changes: 42 additions & 0 deletions dist/src/Classes/Category.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { CategoryNameType } from "../Typings/types";
import getCategory from "../Functions/getCategory";
/**
* @class Class for anything trivia category related.
*/
export default class Category {
/**
* An array of all category names. Use `Category.random()` for a random pick.
*/
static allNames: CategoryNameType[];
/**
* Decodes a URLLegacy, URL3968 or Base64 category name.
* @param {string} str string to decode.
* @returns {string} The decoded category name.
*/
static decodeEncodedCategoryName(str: string): CategoryNameType | null;
/**
* Fetches a trivia category's data. Duplicate of `getCategory()`.
* @param {CategoryResolvable} arg An argument resolving to a trivia category.
* @returns {Promise<CategoryData>} The data of the category.
*/
static getCategory: typeof getCategory;
/**
* Returns a category id when given it's name.
* @param {CategoryNameType} name The name of the category.
* @returns {number | null} The id if resolvable.
*/
static idByName(name: CategoryNameType): number | null;
/**
* Returns a category name when given it's id.
* @param {number} id The id of the category.
* @returns {CategoryNameType | null} The name if resolvable.
*/
static nameById(id: number): CategoryNameType | null;
/**
* Picks a random category name or id.
* @param {'name' | 'id'} resolvableType The kind of resolvable to return (default `'name'`).
* @returns {CategoryNameType | number} A random category id or name.
*/
static random(resolvableType: "name"): CategoryNameType;
static random(resolvableType: "id"): number;
}
62 changes: 62 additions & 0 deletions dist/src/Classes/Category.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var enums_1 = require("../Typings/enums");
var getCategory_1 = require("../Functions/getCategory");
var Util_1 = require("./Util");
/**
* @class Class for anything trivia category related.
*/
var Category = /** @class */ (function () {
function Category() {
}
/**
* Decodes a URLLegacy, URL3968 or Base64 category name.
* @param {string} str string to decode.
* @returns {string} The decoded category name.
*/
Category.decodeEncodedCategoryName = function (str) {
return ([
Util_1.default.decodeBase64(str),
Util_1.default.decodeUrl3968(str),
Util_1.default.decodeUrlLegacy(str),
].find(function (str) { return Category.allNames.includes(str); }) || null);
};
/**
* Returns a category id when given it's name.
* @param {CategoryNameType} name The name of the category.
* @returns {number | null} The id if resolvable.
*/
Category.idByName = function (name) {
var id = Category.allNames.indexOf(name);
return id > -1 ? id + 9 : null;
};
/**
* Returns a category name when given it's id.
* @param {number} id The id of the category.
* @returns {CategoryNameType | null} The name if resolvable.
*/
Category.nameById = function (id) {
var name = Category.allNames[id - 9];
return name !== undefined ? name : null;
};
Category.random = function (resolvableType) {
if (resolvableType === undefined)
resolvableType = "name";
var name = Category.allNames[Math.floor(Math.random() * Category.allNames.length)];
if (resolvableType === "id")
return Category.idByName(name);
return name;
};
/**
* An array of all category names. Use `Category.random()` for a random pick.
*/
Category.allNames = Object.keys(enums_1.CategoryNames).filter(function (key) { return isNaN(+key); });
/**
* Fetches a trivia category's data. Duplicate of `getCategory()`.
* @param {CategoryResolvable} arg An argument resolving to a trivia category.
* @returns {Promise<CategoryData>} The data of the category.
*/
Category.getCategory = getCategory_1.default;
return Category;
}());
exports.default = Category;
19 changes: 19 additions & 0 deletions dist/src/Classes/Constructor.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { CategoryData, Question, RawCategoryResponse, RawQuestion } from "../Typings/interfaces";
/**
* @class Class for transforming raw API data to developer friendly data.
* @private
*/
export default class Constructor {
/**
* Parses a raw category to be more JavaScript friendly and less verbose.
* @param {RawCategoryResponse} rawCategoryData The raw category.
* @returns {CategoryData}
*/
static category(rawCategoryData: RawCategoryResponse): CategoryData;
/**
* Parses each object in a raw question array to be more JavaScript friendly.
* @param {RawQuestion[]} rawQuestions An array of raw questions.
* @returns {Question<unknown>[]}
*/
static questions(rawQuestions: RawQuestion[]): Question<unknown>[];
}
79 changes: 79 additions & 0 deletions dist/src/Classes/Constructor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"use strict";
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
var Category_1 = require("./Category");
var Util_1 = require("./Util");
/**
* @class Class for transforming raw API data to developer friendly data.
* @private
*/
var Constructor = /** @class */ (function () {
function Constructor() {
}
/**
* Parses a raw category to be more JavaScript friendly and less verbose.
* @param {RawCategoryResponse} rawCategoryData The raw category.
* @returns {CategoryData}
*/
Constructor.category = function (rawCategoryData) {
return {
id: rawCategoryData.category_id,
name: Category_1.default.nameById(rawCategoryData.category_id),
questionCount: {
total: rawCategoryData.category_question_count.total_question_count,
easy: rawCategoryData.category_question_count.total_easy_question_count,
medium: rawCategoryData.category_question_count.total_medium_question_count,
hard: rawCategoryData.category_question_count.total_hard_question_count,
},
};
};
/**
* Parses each object in a raw question array to be more JavaScript friendly.
* @param {RawQuestion[]} rawQuestions An array of raw questions.
* @returns {Question<unknown>[]}
*/
Constructor.questions = function (rawQuestions) {
return rawQuestions.map(function (question) {
return {
value: question.question,
category: {
id: Category_1.default.idByName(Category_1.default.decodeEncodedCategoryName(question.category)),
name: question.category,
getData: function () {
return Category_1.default.getCategory(this.id);
},
},
type: question.type,
difficulty: question.difficulty,
correctAnswer: question.type === "multiple"
? question.correct_answer
: question.correct_answer.toLowerCase(),
incorrectAnswers: question.type === "multiple"
? question.incorrect_answers
: question.incorrect_answers[0].toLowerCase(),
allAnswers: Util_1.default.shuffleArray(__spreadArray([
question.correct_answer
], (question.type === "multiple"
? question.incorrect_answers
: question.incorrect_answers.map(function (s) { return s.toLowerCase(); })), true)),
checkAnswer: function (str, caseSensitive) {
if (caseSensitive === void 0) { caseSensitive = false; }
if (!caseSensitive) {
return str.toLowerCase() === this.correctAnswer.toLowerCase();
}
return str === this.correctAnswer;
},
};
});
};
return Constructor;
}());
exports.default = Constructor;
11 changes: 11 additions & 0 deletions dist/src/Classes/OpenTDBError.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { ErrorResponse } from "../Typings/interfaces";
/**
* @class OpenTDB error constructor
* @private
*/
export default class OpenTDBError extends TypeError {
/**
* @param {ErrorResponse} error A basic header-text error object.
*/
constructor(error: ErrorResponse);
}
34 changes: 34 additions & 0 deletions dist/src/Classes/OpenTDBError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @class OpenTDB error constructor
* @private
*/
var OpenTDBError = /** @class */ (function (_super) {
__extends(OpenTDBError, _super);
/**
* @param {ErrorResponse} error A basic header-text error object.
*/
function OpenTDBError(error) {
var _this = _super.call(this, error.text) || this;
_this.name = "OpenTDBError [".concat(error.header, "]");
return _this;
}
return OpenTDBError;
}(TypeError));
exports.default = OpenTDBError;
Loading