Skip to content

Commit

Permalink
blazed.js version 1.0.34
Browse files Browse the repository at this point in the history
Patch Notes -
1. Fixed some bugs
2. Improved error handling
3. Fixed some known issues related to the dns lookup (resolve()) function. Check docs for the usage
  • Loading branch information
BlazeInferno64 authored Oct 25, 2024
1 parent 0b67b18 commit 3b2a842
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 88 deletions.
2 changes: 1 addition & 1 deletion lib/node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ blazed.resolve({
// Resolving DNS using blazed.resolve() without specified ip format.
// Starting the request to resolve the hostname.

blazed.request({
blazed.resolve({
/**
* The hostname to resolve (e.g., 'https://www.google.com').
* Note: if you omit the protocol (http/https), you will get an error of invalid url.
Expand Down
46 changes: 22 additions & 24 deletions lib/node/lib/blazed.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const emitter = new EventEmitter();

const urlParser = require("./utils/url-parser");
const headerParser = require("./utils/header-parser");
const httpErrors = require("./utils/errors");
const utilErrors = require("./utils/errors");
const dnsResolver = require("./utils/dns");

const packageJson = require("../package.json");
Expand All @@ -27,6 +27,7 @@ const HTTP_METHODS = Object.freeze({
PATCH: 'PATCH',
});

let custom;

/**
* Backbone of blazed.js for performing HTTP requests
Expand All @@ -44,7 +45,7 @@ const makeRequest = (method, url, data, headers = {}, redirectCount = 5) => {
return new Promise(async (resolve, reject) => {
if (!url) {
const error = new Error(`Empty URL Provided!`);
error.name = "Null URL Error";
error.name = "Null_URL_Error";
error.code = "ENULLURL"
error.message = `HTTP Request '${method}' failed due to empty URL`;
return reject(error);
Expand Down Expand Up @@ -103,8 +104,8 @@ const makeRequest = (method, url, data, headers = {}, redirectCount = 5) => {
}
})
request.on('error', async (error) => {
// Process the http error using the 'httpErrors' util tool.
return await httpErrors.processError(error, url);
// Process the http error using the 'utilErrors' util tool.
return await utilErrors.processError(error, url);
});
if (data) {
request.write(requestOptions.body);
Expand Down Expand Up @@ -159,17 +160,15 @@ const handleResponse = (response, resolve, reject, redirectCount = 5, originalUr
response.on('data', (chunk) => {
responseData += chunk;
});
response.on('end', () => {
response.on('end', async() => {
const contentType = response.headers['content-type'];
if (contentType?.includes('application/json')) {
try {
const parsedData = JSON.parse(responseData);
if (!parsedData) {
const error = new Error(`Empty JSON Response`)
error.name = `EmptyResponseError`;
error.code = `ERESNULL`; // Set a code named ERESNULL for indicating null response
error.message = `The JSON response received from '${originalUrl}' is empty and doesn't contains any data!`;
return reject(error);
if (!parsedData || Object.keys(parsedData).length === 0) {
const error = 'JSON_NULL';
custom = true;
return reject(await utilErrors.processError(error, originalUrl, false, false, custom));
}
responseObject.data = parsedData;
responseObject.status = response.statusCode;
Expand All @@ -180,14 +179,12 @@ const handleResponse = (response, resolve, reject, redirectCount = 5, originalUr
emitter.emit("afterRequest", originalUrl, responseObject);
return resolve(responseObject);
} catch (error) {
if (!responseData) {
const error = new Error(`Empty Response`)
error.name = `EmptyResponseError`;
error.code = `ERESNULL`; // Set a code named ERESNULL for indicating null response
error.message = `The response received from '${originalUrl}' is empty and doesn't contains any data!`;
return reject(error);
if (!responseData || responseData.trim() === "") {
const error = `RES_NULL`;
custom = true;
return reject(utilErrors.processError(error, originalUrl, false, false, custom));
}
return reject(new Error('Failed to parse JSON!'));
return reject(error);
}
} else {
responseObject.data = responseData;
Expand Down Expand Up @@ -239,11 +236,11 @@ const handleResponse = (response, resolve, reject, redirectCount = 5, originalUr
}
return resolve(makeRequest(method, redirectUrl, null, headers, redirectCount - 1));
} else {
const err = new Error(`Too many redirects!`);
err.message = `Too many redirects occured! Redirect count: ${redirectCount}`;
err.name = `Too many redirects error`;
err.code = `EREDIRECTERR`;
return reject(err);
const error = 'RED_ERR';
custom = true;
return reject(async () => {
await utilErrors.processError(error, false, false, false, redirectCount)
});
}

}
Expand Down Expand Up @@ -338,9 +335,10 @@ const validateHeaderValue = async (name, value) => {
*/

const resolve = async (hostObject) => {
if (typeof hostObject !== "object") return new Error(`Expected a host object with properties as hostname and ip address format`)
const url = hostObject.hostname;
const format = hostObject.format;
const parsedURL = new URL(url);
const parsedURL = await urlParser.parseThisURL(url);
return await dnsResolver.lookupForIp(parsedURL.hostname, format, url);
}
/**
Expand Down
2 changes: 1 addition & 1 deletion lib/node/lib/utils/dns.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const lookupForIp = async(hostname, type) => {
return reject(await processError(error, hostname, 'Yes'));
}
} else {
return reject(`Unknown ip address format specified! Available formats - IPv4, IPv6`);
return reject(`Unknown ip address format specified!\nAvailable formats - IPv4, IPv6`);
}
}
})
Expand Down
49 changes: 46 additions & 3 deletions lib/node/lib/utils/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @param {Object} error - The HTTP error you want to process.
* @returns {Promise<Object>} returns the processed error object as a promise.
*/
const processError = (error, url, dns) => {
const processError = (error, url, dns, header, custom) => {
return new Promise((resolve, reject) => {
if (error.code === 'ENOTFOUND') {
const err = new Error(`DNS Resolution Error`);
Expand Down Expand Up @@ -69,8 +69,51 @@ const processError = (error, url, dns) => {
err.name = "Network_Down_Error";
err.message = `The network is down`;
return reject(err);
}
else {
} else if(error.code === 'ERR_INVALID_HTTP_TOKEN'){
const err = new TypeError();
err.code = 'ERR_INVALID_HTTP_HEADER';
err.message = `Header name must be a valid HTTP token! Recieved token: ["${header}"]`;
return reject(error);
} else if(error.code === 'ERR_HTTP_INVALID_HEADER_VALUE'){
const value = header.value;
const name = header.name;
const err = new TypeError(`Invalid Header Value`);
err.code = error.code;
err.message = `Invalid value: ${value} for header "${name}"`;
return reject(error);
} else if(error.code === 'ERR_INVALID_CHAR') {
const value = header.value;
const name = header.name;
const err = new TypeError(`Invalid Header Value`);
err.code = error.code;
err.message = `Invalid character: ${value} in header content ["${name}"]`;
return reject(error);
} else if(error.code === 'ERR_INVALID_URL'){
const err = new TypeError('Invalid URL!');
err.message = `Invalid URL provided "${url}"`;
err.code = error.code;
err.input = url;
err.name = `URL_Parsing_Error`;
return reject(err);
} else if (error == 'JSON_NULL' && custom){
const err = new Error(`Empty JSON Response`);
err.name = `Empty_JSON_Response`;
err.code = `ERESNULL`; // Set a code named ERESNULL for indicating null response
err.message = `The JSON response received from '${url}' is empty and doesn't contains any data!`;
return reject(err);
} else if (error == 'RES_NULL' && custom){
const err = new Error(`Empty Response`);
err.name = `Empty_Response`;
err.code = `ERESNULL`; // Set a code named ERESNULL for indicating null response
err.message = `The response received from '${url}' is empty and doesn't contains any data!`;
return reject(err);
} else if (error === 'RED_ERR'){
const err = new Error(`Too many redirects!`);
err.message = `Too many redirects occured! Redirect count: ${custom}`;
err.name = `Excessive_Redirects_Error`;
err.code = `ERR_TOO_MANY_REDIRECTS`;
return reject(err);
} else {
return reject(error);
}
})
Expand Down
32 changes: 9 additions & 23 deletions lib/node/lib/utils/header-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"use strict";

const { validateHeaderName, validateHeaderValue } = require("http");
const { resolve } = require("path");
const { processError } = require("./errors");

/**
*
Expand All @@ -11,18 +11,12 @@ const { resolve } = require("path");
*/

const parseThisHeaderName = (header) => {
return new Promise((resolve, reject) => {
return new Promise(async(resolve, reject) => {
try {
validateHeaderName(header);
return resolve(true);
} catch (error) {
if(error.code === 'ERR_INVALID_HTTP_TOKEN') {
const error = new TypeError();
error.code = 'ERR_INVALID_HTTP_HEADER';
error.message = `Header name must be a valid HTTP token! Recieved token: ["${header}"]`;
return reject(error);
}
return reject(error);
return reject(await processError(error, false, false, header))
}
})
}
Expand All @@ -35,7 +29,7 @@ const parseThisHeaderName = (header) => {
*/

const parseThisHeaderValue = (name, value) => {
return new Promise((resolve, reject) => {
return new Promise(async(resolve, reject) => {
if(!name) {
const error = new TypeError();
error.code = 'ENULLHEADER';
Expand All @@ -49,27 +43,19 @@ const parseThisHeaderValue = (name, value) => {
return reject(error);
}
try {

await parseThisHeaderName(name);
validateHeaderValue(name, value);
const headerObj = {
"name": name,
"value": value
}
return resolve(headerObj);
} catch (err) {
if(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE') {
const error = new TypeError(`Invalid Header Value`);
error.code = err.code;
error.message = `Invalid value: ${value} for header "${name}"`;
return reject(error);
}
if(err.code === 'ERR_INVALID_CHAR') {
const error = new TypeError(`Invalid Header Value`);
error.code = err.code;
error.message = `Invalid character: ${value} in header content ["${name}"]`;
return reject(error);
const errHeaderObject = {
"name": name,
"value": value
}
return reject(err);
return reject(await processError(err, false, false, errHeaderObject));
}
})
}
Expand Down
36 changes: 5 additions & 31 deletions lib/node/lib/utils/url-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

"use strict";

const { processError } = require("./errors");

/**
* Represents a parsed URL.
* @typedef {Object} ParsedURL
Expand All @@ -27,7 +29,7 @@ const parseThisURL = (url) => {
if (!url) {
throw new Error('No URL Provided!');
}
return new Promise((resolve, reject) => {
return new Promise(async(resolve, reject) => {
try {
const parsedURL = new URL(url);
const urlData = {
Expand All @@ -44,39 +46,11 @@ const parseThisURL = (url) => {
};
return resolve(urlData);
} catch (error) {
if (error.code === 'ERR_INVALID_URL') {
const err = new TypeError('Invalid URL!');
err.message = `Invalid URL provided "${url}"`;
err.code = error.code;
err.input = url;
err.name = `URL Error`
return reject(err);
}
return reject(error);
return reject(await processError(error,url,false,false))
}
});
};

/**
* Checks if a given string is a valid URL.
* @param {string} url The URL to check.
* @returns {boolean} True if the URL is valid, false otherwise.
*/
const isValidURL = (url) => {
return new Promise((resolve, reject) => {
try {
new URL(url);
return resolve(true);
} catch (error) {
const err = new TypeError(`Not a valid URL`);
err.code = error.code;
err.message = `${url} isn't a valid URL!`;
return reject(err);
}
})
}

module.exports = {
parseThisURL,
isValidURL
parseThisURL
}
4 changes: 2 additions & 2 deletions lib/node/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/node/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "blazed.js",
"version": "1.0.33",
"version": "1.0.34",
"main": "index.js",
"types": "typings/index.d.ts",
"scripts": {
Expand Down
4 changes: 2 additions & 2 deletions lib/node/typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ interface blazed {
* @example
* // Example usage demonstrating DNS resolving with specified format
* // Starting the request
* blazed.request({
* blazed.resolve({
* format: "IPv6",
* hostname: "https://www.google.com"
* }).then(res => {
Expand All @@ -241,7 +241,7 @@ interface blazed {
*
* // Example usage demonstrating DNS resolving without specified format
* // Starting the request
* blazed.request({
* blazed.resolve({
* hostname: "https://www.google.com"
* }).then(res => {
* return console.log(res.data);
Expand Down

0 comments on commit 3b2a842

Please sign in to comment.