UNPKG

dadjokes-wrapper

Version:
89 lines (80 loc) 1.77 kB
const fs = require('fs'); const got = require('got'); const QuickLRU = require('quick-lru'); const { name, version } = require('./package.json'); const header = `${name}/${version} (https://github.com/Neos-Duswell/dadjokes-wrapper)`; const cache = new QuickLRU({ maxSize: 1000 }); /** * @type {DadJokes} */ class DadJokes { /** * @param {string} [baseURL] */ constructor(baseURL = 'https://icanhazdadjoke.com/') { /** * @type {string} */ this.baseURL = baseURL; } /** * @return {Promise} */ randomJoke() { return got.get(this.baseURL, { json: true, headers: { 'user-agent': header } }).then(({ body }) => body.joke).catch(e => e); } /** * @return {Promise} */ randomSlackJoke() { return got.get(`${this.baseURL}slack`, { json: true, headers: { 'user-agent': header } }).then(({ body }) => body).catch(e => e); } /** * @param {string} id * @return {Promise} */ jokeById(id) { return got.get(`${this.baseURL}j/${id}`, { cache: cache, json: true, headers: { 'user-agent': header } }).then(({ body }) => body.joke).catch(e => e); } /** * @async * @param {string} id * @return {Promise} */ async jokeImgById(id) { const response = await got.stream(`${this.baseURL}j/${id}.png`) .pipe(fs.createWriteStream(`${id}.png`)); return response; } /** * @param {string} query * @return {Promise} */ searchJoke(query) { return got.get(`${this.baseURL}search`, { cache: cache, query, json: true, headers: { 'user-agent': header } }).then(({ body }) => body).catch(e => e); } } module.exports = DadJokes;