Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

node_modules
143 changes: 143 additions & 0 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,26 @@ const net = require('net')
//
// })

/**
* Finds the first occurrence of a target character in a given string.
*
* @param {string} req - The string to search within.
* @param {string} target - The character to find in the string.
* @returns {number} The index of the first occurrence of the target character,
* or -1 if the target character is not found.
*
* @example
*
* const myString = "Hello, world!";
* const targetChar = "o";
* const index = findFirstBrac(myString, targetChar);
*
* if (index !== -1) {
* console.log(`The first occurrence of '${targetChar}' is at index ${index}.`);
* } else {
* console.log(`The character '${targetChar}' is not found in the string.`);
* }
*/
function findFirstBrac (req, target) {
for (let i = 0; i < req.length; i++) {
if (req[i] === target) {
Expand All @@ -23,6 +43,32 @@ function findFirstBrac (req, target) {
}

// POST /api/users HTTP/1.1
/**
* Parses an HTTP request string and extracts its components.
*
* @param {string} request - The HTTP request string to parse.
* @returns {Promise<Object>} A promise that resolves to an object containing the HTTP method, path, version, and body (if applicable).
*
* @example
* // Example HTTP request string
const httpRequest = `POST /api/data HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 51

{
"name": "John Doe",
"email": "john.doe@example.com"
}`;

// Call the httpParser function with the example request
httpParser(httpRequest).then(parsedRequest => {
console.log(parsedRequest);
}).catch(error => {
console.error('Error parsing HTTP request:', error);
});
*
*/
async function httpParser (request) {
const req = new Object()
const requestString = request.split('\n')
Expand Down Expand Up @@ -52,6 +98,27 @@ httpParser(request).then((data) => {

})

/**
* Stores a key-value pair from a request string into a JSON object.
*
* @param {Array} req - The request string split into an array of characters.
* @param {Object} httpJSON - The JSON object to store the key-value pair.
* @returns {Array} The modified request array after extracting the key-value pair.
*
* @example
* // Example request string
const requestString = "key1:value1,key2:value2";
const reqArray = requestString.split('');
const httpJSON = {};

// Extract key-value pairs
while (reqArray.length > 0) {
storePair(reqArray, httpJSON);
}

console.log(httpJSON); // Output: { key1: 'value1', key2: 'value2' }

*/
function storePair (req, httpJSON) {
let key = ''
let i = 0
Expand Down Expand Up @@ -79,6 +146,18 @@ function storePair (req, httpJSON) {
return req
}

/**
* Parses a JSON body string and converts it into a JSON object.
*
* @param {string} body - The JSON body string to parse.
* @returns {Object} The parsed JSON object.
*
* @example
* const jsonString = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
const parsedObject = JSONbodyParser(jsonString);
console.log(parsedObject); // Output: { key1: 'value1', key2: 'value2' }

*/
function JSONbodyParser (body) {
const req = body.split('')
const httpJSON = new Object()
Expand All @@ -105,6 +184,30 @@ function JSONbodyParser (body) {
return httpJSON
}

/**
* Extracts the body of an HTTP request starting from a given position.
*
* @param {Array} req - The request string split into an array of lines.
* @param {number} pos - The position to start extracting the body.
* @returns {Promise<string>} A promise that resolves to the extracted body string.
*
* @example
* const httpRequest = `POST /api/data HTTP/1.1
Host: example.com
Content-Type: application/json

{
"name": "John Doe",
"age": 30
}`;

const requestLines = httpRequest.split('\n');
const bodyStartPos = findFirstBrac(requestLines, '{');

HTTPbody(requestLines, bodyStartPos).then((body) => {
console.log('Extracted Body:', body);
});
*/
function HTTPbody (req, pos) {
flag = 0
let body = ''
Expand All @@ -126,6 +229,16 @@ function HTTPbody (req, pos) {
})
}

/**
* Parses a query string from a URL and extracts its components.
*
* @param {string} request - The URL containing the query string.
*
* @example
const url = 'https://example.com?name=JohnDoe&age=25&city=NewYork';
const parsedQuery = queryParser(url);
console.log(parsedQuery); // Output: { name: 'JohnDoe', age: '25', city: 'NewYork' }
*/
function queryParser (request) {
const req = new Object()
const pos = findFirstBrac(request, '?')
Expand All @@ -135,6 +248,18 @@ function queryParser (request) {
}
}

/**
* Stores a query string into a JSON object.
*
* @param {string} query - The query string to parse.
* @returns {Object} The parsed query string as a JSON object.
*
* @example
* // Example usage
const queryString = "key1=value1&key2=value2";
const parsedQuery = storeQuery(queryString);
console.log(parsedQuery); // Output: { key1: 'value1', key2: 'value2' }
*/
function storeQuery (query) {
const req = query.split('')
const httpQueryJSON = new Object()
Expand All @@ -156,6 +281,24 @@ function storeQuery (query) {
return httpQueryJSON
}

/**
* Stores a key-value pair from a query string into a JSON object.
*
* @param {Array} req - The query string split into an array of characters.
* @returns {Object} The JSON object containing the key-value pair.
*
* @example
* const queryString = "key1=value1&key2=value2";
const queryArray = queryString.split('');
let queryJSON = {};

while (queryArray.length > 0) {
const pair = queryStorePair(queryArray);
queryJSON = { ...queryJSON, ...pair };
}

console.log(queryJSON); // Output: { key1: 'value1', key2: 'value2' }
*/
function queryStorePair (req) {
let key = ''
let i = 0
Expand Down
71 changes: 71 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@

/**
* Finds the index of the first occurrence of the target character in the given string.
* @param {string} req - The string to search through.
* @param {string} target - The character to find in the string.
* @returns {number} The index of the target character or -1 if not found.
*
* @example
* const index = findFirstBrac('Hello, World!', 'o');
*/
function findFirstBrac (req, target) {
for (let i = 0; i < req.length; i++) {
if (req[i] === target) {
Expand All @@ -7,6 +17,15 @@ function findFirstBrac (req, target) {
return -1
}

/**
* Parses the HTTP body from a given position.
* @param {string} req - The HTTP request as a string.
* @param {number} pos - The position in the string to start parsing.
* @returns {Promise<string>} A promise that resolves to the cleaned-up body.
*
* @example
* const body = await HTTPbody(req, pos);
*/
function HTTPbody (req, pos) {
let flag = 0
let body = ''
Expand All @@ -30,6 +49,14 @@ function HTTPbody (req, pos) {
})
}

/**
* Cleans up the body content by trimming spaces and standardizing spacing around colons and commas.
* @param {string} body - The body content to clean up.
* @returns {string} body - The cleaned-up body.
*
* @example
* const cleanedBody = cleanUpBody(body);
*/
function cleanUpBody (body) {
// Trim leading and trailing spaces
body = body.trim()
Expand All @@ -43,6 +70,14 @@ function cleanUpBody (body) {
return body
}

/**
* Parses a JSON-like HTTP body into an object.
* @param {string} body - The HTTP body content as a string.
* @returns {Object} The parsed JSON object.
*
* @example
* const parsedBody = JSONbodyParser(body);
*/
function JSONbodyParser (body) {
const req = body.split('')
const httpJSON = new Object()
Expand All @@ -67,6 +102,16 @@ function JSONbodyParser (body) {
return httpJSON
}


/**
* Stores key-value pairs in the provided JSON object.
* @param {Array<string>} req - The remaining request characters.
* @param {Object} httpJSON - The JSON object to store the parsed data.
* @returns {Array<string>} The remaining unprocessed request characters.
*
* @example
* storePair(req, httpJSON);
*/
function storePair (req, httpJSON) {
let key = ''
let value = ''
Expand Down Expand Up @@ -100,6 +145,15 @@ function storePair (req, httpJSON) {
return req
}


/**
* Parses primitive values from the request array.
* @param {Array<string>} req - The remaining request characters.
* @returns {string|number} The parsed value, either as a string or number.
*
* @example
* const parsedValue = parseValue(req);
*/
// Helper function to parse primitive values (strings, numbers, etc.)
function parseValue (req) {
let value = ''
Expand Down Expand Up @@ -137,6 +191,14 @@ function parseValue (req) {
return isString ? value.trim() : value.trim() // Return the value
}

/**
* Parses a query string from a request URL into a JSON object.
* @param {string} request - The request URL as a string.
* @returns {Object} The parsed query parameters as a JSON object.
*
* @example
* const queryParams = queryParser(request);
*/
function queryParser (request) {
const httpQueryJSON = new Object()
const queryStart = request.indexOf('?')
Expand All @@ -159,6 +221,15 @@ function queryParser (request) {

const mimeDb = require('./mimeDb') // Adjust the path as needed


/**
* Looks up the MIME type based on the file extension.
* @param {string} extension - The file extension to look up.
* @returns {string} The MIME type or 'application/octet-stream' if not found.
*
* @example
* const mimeType = lookupMimeType('application/json');
*/
function lookupMimeType (extension) {
const mimeType = Object.keys(mimeDb).find(type =>
mimeDb[type].extensions.includes(extension)
Expand Down
Loading