Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
sefinek committed May 28, 2024
1 parent 91276a2 commit 0c36230
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 41 deletions.
22 changes: 15 additions & 7 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
declare module 'random-fox-img' {
interface FoxImageData {
interface Info {
category: string;
endpoint: string;
}

interface GetRandomFox {
success: boolean;
status: number;
info: {
category: string;
endpoint: string;
};
info: Info;
message: string;
}

function getRandomFox(): Promise<FoxImageData>;
export = getRandomFox;
/**
* Retrieves a random fox object from the specified API.
*
* @async
* @returns {Promise<GetRandomFox>} A promise that resolves with a random fox object on success or rejects with an error on failure.
* @throws {Error} If there's an error in making the request, parsing JSON data, or if the API responds with a non-200 status code.
*/
export function getRandomFox(): Promise<GetRandomFox>;
}
55 changes: 21 additions & 34 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,43 +18,30 @@ const headers = {
'X-XSS-Protection': '1; mode=block'
};

/**
* Retrieves a random fox object from the specified API.
*
* @async
* @returns {Promise<object>} A promise that resolves with a random fox object on success or rejects with an error on failure.
* @throws {Error} If there's an error in making the request, parsing JSON data, or if the API responds with a non-200 status code.
*/
async function getRandomFox() {
return new Promise((resolve, reject) => {
const req = https.get(apiUrl, { headers }, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`Request failed with status code ${res.statusCode}`));
return;
const getRandomFox = () => new Promise((resolve, reject) => {
const req = https.get(apiUrl, { headers }, res => {
if (res.statusCode !== 200) {
reject(new Error(`Request failed with status code ${res.statusCode}`));
return;
}

const data = [];

res.on('data', chunk => data.push(chunk));

res.on('end', () => {
try {
const catData = JSON.parse(Buffer.concat(data).toString());
resolve(catData);
} catch (err) {
reject(new Error(`Error parsing JSON data: ${err.message}`));
}

let data = '';

res.on('data', chunk => {
data += chunk;
});

res.on('end', () => {
try {
const foxData = JSON.parse(data);
resolve(foxData);
} catch (err) {
reject(new Error('Error parsing JSON data'));
}
});
});
});

req.on('error', err => {
reject(new Error(`Error making the request: ${err.message}`));
});
req.on('error', err => reject(new Error(`Error making the request: ${err.message}`)));

req.end();
});
}
req.end();
});

module.exports = getRandomFox;

0 comments on commit 0c36230

Please sign in to comment.