Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

open-trivia-db

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

open-trivia-db - npm Package Compare versions

Comparing version 1.0.2 to 2.0.0

dist/src/classes/Category.d.ts

22

dist/index.d.ts

@@ -1,11 +0,11 @@

import Category from "./src/Classes/Category";
import { OpenTDBError, OpenTDBResponse } from "./src/Classes/CustomErrors";
import OpenTDBUtil from "./src/Classes/OpenTDBUtil";
import Session from "./src/Classes/Session";
import Validator from "./src/Classes/Validator";
import getCategoryData from "./src/Functions/getCategoryData";
import getQuestions from "./src/Functions/getQuestions";
import { CategoryIdResolvable, CategoryNameResolvable, CategoryName, CategoryNameVersion, CategoryNamePretty, CategoryNameStrict, CategoryResolvable, CategoryResolvableType, NumberResolvable, OpenTDBResponseCode, QuestionDifficulty, QuestionOptionsDefaults, QuestionType, QuestionEncoding, QuestionVersion, Questions } from './src/Typings/types';
import { OpenTDBResponseDefault, OpenTDBResponseSession, RawCategoryData, CategoryData, OpenTDBResponseCategoryData, Question, QuestionBase, QuestionOptions, RawQuestion } from './src/Typings/interfaces';
import { CategoryNamesStrict, CategoryNameVersions, CategoryNamesPretty, QuestionAmountRange, QuestionDifficulties, QuestionEncodings, QuestionTypes, QuestionVersions } from './src/Typings/enums';
export { Category, OpenTDBError, OpenTDBResponse, OpenTDBUtil, Session, Validator, getCategoryData, getQuestions, CategoryIdResolvable, CategoryNameResolvable, CategoryName, CategoryNameVersion, CategoryNamePretty, CategoryNameStrict, CategoryResolvable, CategoryResolvableType, NumberResolvable, OpenTDBResponseCode, QuestionDifficulty, QuestionOptionsDefaults, QuestionType, QuestionEncoding, QuestionVersion, Questions, OpenTDBResponseDefault, OpenTDBResponseSession, RawCategoryData, CategoryData, OpenTDBResponseCategoryData, Question, QuestionBase, QuestionOptions, RawQuestion, CategoryNamesStrict, CategoryNameVersions, CategoryNamesPretty, QuestionAmountRange, QuestionDifficulties, QuestionEncodings, QuestionTypes, QuestionVersions };
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 { CategoryNameType, CategoryResolvable, Dictionary, ErrorCode, 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, CategoryNameType, CategoryResolvable, Dictionary, ErrorCode, QuestionDifficultyType, QuestionEncodingType, QuestionTypeType, ResponseCode, SimpleDictionary, ExtendedDictionary };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuestionVersions = exports.QuestionTypes = exports.QuestionEncodings = exports.QuestionDifficulties = exports.QuestionAmountRange = exports.CategoryNamesPretty = exports.CategoryNameVersions = exports.CategoryNamesStrict = exports.getQuestions = exports.getCategoryData = exports.Validator = exports.Session = exports.OpenTDBUtil = exports.OpenTDBResponse = exports.OpenTDBError = exports.Category = void 0;
var Category_1 = require("./src/Classes/Category");
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 CustomErrors_1 = require("./src/Classes/CustomErrors");
Object.defineProperty(exports, "OpenTDBError", { enumerable: true, get: function () { return CustomErrors_1.OpenTDBError; } });
Object.defineProperty(exports, "OpenTDBResponse", { enumerable: true, get: function () { return CustomErrors_1.OpenTDBResponse; } });
var OpenTDBUtil_1 = require("./src/Classes/OpenTDBUtil");
exports.OpenTDBUtil = OpenTDBUtil_1.default;
var Session_1 = require("./src/Classes/Session");
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 Validator_1 = require("./src/Classes/Validator");
exports.Validator = Validator_1.default;
var getCategoryData_1 = require("./src/Functions/getCategoryData");
exports.getCategoryData = getCategoryData_1.default;
var getQuestions_1 = require("./src/Functions/getQuestions");
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, "CategoryNamesStrict", { enumerable: true, get: function () { return enums_1.CategoryNamesStrict; } });
Object.defineProperty(exports, "CategoryNameVersions", { enumerable: true, get: function () { return enums_1.CategoryNameVersions; } });
Object.defineProperty(exports, "CategoryNamesPretty", { enumerable: true, get: function () { return enums_1.CategoryNamesPretty; } });
Object.defineProperty(exports, "QuestionAmountRange", { enumerable: true, get: function () { return enums_1.QuestionAmountRange; } });
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, "QuestionVersions", { enumerable: true, get: function () { return enums_1.QuestionVersions; } });
Object.defineProperty(exports, "Routes", { enumerable: true, get: function () { return enums_1.Routes; } });
{
"name": "open-trivia-db",
"version": "1.0.2",
"description": "A wrapper for the Open Trivia Database API. Built with TypeScript, works with VanillaJS.",
"version": "2.0.0",
"description": "A small and simple wrapper for the Open Trivia Database API.",
"keywords": [

@@ -28,4 +28,4 @@ "opentriviadatabase",

"files": [
"typings",
"dist"
"dist",
"typings"
],

@@ -42,12 +42,12 @@ "repository": {

"devDependencies": {
"@types/jest": "^27.5.1",
"@types/node": "^17.0.33",
"jest": "^28.1.0",
"nodemon": "^2.0.16",
"prettier": "^2.6.2",
"ts-jest": "^28.0.2"
"@types/jest": "^27.5.2",
"@types/node": "^17.0.45",
"jest": "^28.1.3",
"nodemon": "^2.0.20",
"prettier": "^2.7.1",
"ts-jest": "^28.0.8"
},
"engines": {
"node": ">=14.0.0"
"node": ">=18.0.0"
}
}
![OpenTriviaDB](https://i.imgur.com/QBhF5aY.png)
**open-trivia-db** is a small, simple and fast wrapper for [Open Trivia Database](https://opentdb.com/) - A Free to use, user-contributed trivia question database. Built with TypeScript, works with VanillaJS.
![version](https://img.shields.io/npm/v/open-trivia-db)
![downloads](https://img.shields.io/npm/dm/open-trivia-db)
![minisize](https://img.shields.io/bundlephobia/min/open-trivia-db)
![types](https://img.shields.io/npm/types/open-trivia-db)
Documentation: https://github.com/Elitezen/open-trivia-db-wrapper/wiki/Documentation
`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
Support me: https://www.paypal.com/paypalme/alejandromuratalla
## Updates (2.0.0)
- The library received a massive rework through many quality of life changes.
## Updates
### 1.0.2
- Switched from https module to Node Fetch API (now requires Node 18)
- 'Static' and 'Pretty' category names are no more, developers will no longer have to worry about converting through these formats.
# Installation
Ensure you are using Node version 14 or higher and that your enviroment contains the `https` module.
```sh-session
npm i open-trivia-db // Requires NodeJS 18 or higher
- All QuestionOption option types now have respective enums to work with.
npm i open-trivia-db@1.0.1 // Below NodeJS 18
```
- `Category` is now just a class with various static methods for working with categories.
# Example Usage
The following examples make use of the [Async/Await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) syntax. Ensure you are inside an async function, otherwise use promise callbacks.
## Fetching Questions
You can provide `QuestionOptions` to describe the type of questions you want to recieve.
## Example Code
```js
import { Category, getQuestions } from 'open-trivia-db';
import { getQuestions, CategoryNames } from "open-trivia-db";
const questions = await getQuestions({
amount: 50, // 1 - 50
difficulty: 'easy', // or 'medium' or 'hard'
type: 'multiple', // or 'boolean (true/false)
category: Category.allNames.SCIENCE_COMPUTERS
});
amount: 10,
category: CategoryNames.Animals,
difficulty: QuestionDifficulties.Easy,
})
```
### Output
<details>
<summary>Click to view</summary>
```js
## Result
```js
[
{
value: 'What is the code name for the mobile operating system Android 7.0?',
category: 'Science: Computers',
type: 'multiple',
difficulty: 'easy',
correctAnswer: 'Nougat',
incorrectAnswers: [ 'Ice Cream Sandwich', 'Jelly Bean', 'Marshmallow' ],
allAnswers: [ 'Nougat', 'Jelly Bean', 'Marshmallow', 'Ice Cream Sandwich' ],
checkAnswer: [Function: checkAnswer]
}
...
{
value: 'How many teeth does an adult rabbit have?',
category: { id: 27, name: 'Animals', getData: [Function: getData] },
type: 'multiple',
difficulty: 'easy',
correctAnswer: '28',
incorrectAnswers: [ '30', '26', '24' ],
allAnswers: [ '24', '28', '30', '26' ],
checkAnswer: [Function: checkAnswer]
}
...
]
```
</details>
<hr>
# Guide
## Getting Questions
## Working With Categories
Questions can be fetched via the `getQuestions()` function by supplying options such as `amount`, `category`, `difficulty`, `type`, `session` and `encode`.
### Creating Categories with Resolvables
`type`: The kind of questions, such as multiple choice (`"multiple"`) or true/false (`"boolean"`).
You can generate a category class by providing a CategoryResolvable which includes a category's name or id. An instance of Category will allow you to fetch category data and questions relating to the provided resolvable.
```js
let myCategory = new Category(9);
`session`: A session instance or session token. [Learn about sessions](#sessions)
myCategory = new Category('GENERAL_KNOWLEDGE');
`encode`: The encoding of the questions such as `base64`, `urlLegacy`, `url3968` or `none` which is the default.
myCategory = new Category(Category.allNames.GENERAL_KNOWLEDGE);
```
You can apply options via their respective enums.
<hr>
The result will be an array of questions.
### Fetching a Category's API Data
```js
import {
CategoryNames,
QuestionDifficulties,
QuestionTypes,
QuestionEncodings
} from "open-trivia-db";
```js
const data = await myCategory.getData();
getQuestions({
amount: 50,
category: CategoryNames["Entertainment: Japanese Anime & Manga"],
difficulty: QuestionDifficulties.Hard,
type: QuestionTypes.Multiple,
encode: QuestionEncodings.None
})
```
### Output
<details>
<summary>Click to view</summary>
## Getting Categories and Category Data
<hr>
```js
{
id: 9,
name: 'General Knowledge',
questionCounts: {
total: 298,
forEasy: 116,
forMedium: 123,
forHard: 59
}
}
```
A category resolvable can either be a category name or id. Category id's range from 9-32 inclusive, for there are 23 categories.
</details>
<hr>
To jump between resolvables, use `Category.idByName()` and `Category.nameById()`.
### Fetching Questions From a Category
```js
const questions = await myCategory.fetchQuestions({
amount: 1,
difficulty: 'hard'
});
import { Category, CategoryNames } from "open-trivia-db";
// Same outputs as getQuestions()
Category.idByName('Art'); // 25
Category.nameById(25); // 'Art'
```
You can always get information relating to a category by simply passing a resolvable into `getQuestions()` and `getCategoryData()`
### Getting a Category's Data
Use `Category.getCategory()` to get a category's data such as name, id, and question counts.
```js
getQuestions({
category: 9
});
import { Category, CategoryNames } from "open-trivia-db"
getCategoryData('GENERAL_KNOWLEDGE');
Category.getCategory(CategoryNames.Geography)
.then(console.log)
```
// Same as myCategory.fetchQuestions() and .getData()
```js
{
id: 22,
name: 'Geography',
questionCount: {
total: 275,
easy: 80, medium: 139, hard: 56
}
}
```
<hr>
You can also complete a category's data through a question via `Question.category.getData()`
## Using Sessions
A session ensures you do not get duplicate questions.
```js
import { Category, Session, getQuestions } from 'open-trivia-db';
const targetQuestion = questions[0] // from getQuestions()
const session = new Session();
await session.start();
targetQuestion.category.getData()
.then(console.log)
```
## Sessions
A session ensures you are not supplied a question more than once throughout it's lifetime.
const batch1 = await getQuestions({
amount: 10,
category: Category.random(),
difficulty: 'hard',
session
});
Initialize a session and supply the instance into `getQuestions()`. Make sure to await or resolve `Session.start()`.
```js
import { Session } from "open-trivia-db"
const batch2 = await getQuestions({
amount: 10,
category: Category.random(),
difficulty: 'hard',
session
});
const mySession = new Session();
await mySession.start();
const completeBatch = [...batch1, ...batch2]; // All unique!
session.end();
getQuestions({
session: mySession
})
```
**Note:** In respect to the API, it is recommended you generate and save 1 session token for use when testing.
`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()`.
# Documentation
Documentation has been moved to a GitHub Wiki page:
```js
await mySession.reset();
```
https://github.com/Elitezen/open-trivia-db-wrapper/wiki/Documentation
# Support Me
Any tip is greatly appreciated 😀
https://www.paypal.com/paypalme/alejandromuratalla
<hr>
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc