diff --git a/lib/Endpoints.js b/lib/Endpoints.js index 29588d5..2be1f61 100644 --- a/lib/Endpoints.js +++ b/lib/Endpoints.js @@ -1,24 +1,29 @@ -module.exports = [ - 'sfw', - 'nsfw', - 'neko', - 'lewdneko', - 'shinobu', - 'trap', - 'bully', - 'cry', - 'hug', - 'kiss', - 'lick', - 'pat', - 'smug', - 'highfive', - 'nom', - 'bite', - 'slap', - 'wink', - 'poke', - 'dance', - 'cringe', - 'blush' -] \ No newline at end of file +module.exports = { + sfw: [ + 'waifu', + 'neko', + 'shinobu', + 'bully', + 'cry', + 'hug', + 'kiss', + 'lick', + 'pat', + 'smug', + 'highfive', + 'nom', + 'bite', + 'slap', + 'wink', + 'poke', + 'dance', + 'cringe', + 'blush' + ], + nsfw: [ + 'waifu', + 'neko', + 'trap', + 'blowjob' + ] +} \ No newline at end of file diff --git a/lib/WaifuPics.js b/lib/WaifuPics.js index 911d8a9..336a8e0 100644 --- a/lib/WaifuPics.js +++ b/lib/WaifuPics.js @@ -1,13 +1,32 @@ const fetch = require('node-fetch') -const ENDPOINTS = require('./Endpoints.js') +const endpoints = require('./Endpoints.js') const API_URL = 'https://waifu.pics/api' +/** + * @param {string} endpoint An endpoint contained in {@link https://waifu.pics/api/endpoints} + * @returns {Promise} + */ +function request (method, endpoint, options = {}) { + return fetch(`${API_URL}${!endpoint.startsWith('/') ? `/${endpoint}` : endpoint}`, { + method, + ...options, + headers: { + 'Content-Type': 'application/json' + } + }) + .then(parseResponse) +} + async function parseResponse (response) { if (!response.ok) { - const failure = await response.text() + const failure = await response.json() + + throw new Error(failure.message) + } - throw new Error(failure) + if (response.headers.get('content-type').startsWith('text/html')) { + throw new Error(`Category ${response.url.match(/\/\w+/g).pop().substr(1)} not found`) } return response.json() @@ -15,25 +34,25 @@ async function parseResponse (response) { const WaifuPics = { /** - * @param {string} endpoint An endpoint contained in {@link https://waifu.pics/api/endpoints} - * @returns {Promise} + * @returns {Promise} */ - fetch (endpoint) { - return fetch(`${API_URL}${!endpoint.startsWith('/') ? `/${endpoint}` : endpoint}`).then(parseResponse) + endpoints () { + return request('GET', '/endpoints') }, - /** - * @returns {Promise} - */ - endpoints () { - return this.fetch('/endpoints') - } + many: {} } -for (let endpoint of ENDPOINTS) { - WaifuPics[endpoint] = function () { - return this.fetch(endpoint) - } -} +Object.keys(endpoints).forEach((type) => { + WaifuPics[type] = {} + WaifuPics.many[type] = {} + + endpoints[type].forEach((category) => { + const endpoint = `/${type}/${category}` + + WaifuPics[type][category] = () => request('GET', endpoint) + WaifuPics.many[type][category] = (exclude) => request('POST', '/many' + endpoint, { body: JSON.stringify({ exclude }) }) + }) +}) module.exports = WaifuPics \ No newline at end of file