Skip to content

Commit e48ecc7

Browse files
authored
Merge pull request #92 from OAtulA/wiki-84
Wiki #84
2 parents 4ed3901 + 18f2e94 commit e48ecc7

15 files changed

Lines changed: 1642 additions & 1 deletion

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

lib/parser.js

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,26 @@ const net = require('net')
1313
//
1414
// })
1515

16+
/**
17+
* Finds the first occurrence of a target character in a given string.
18+
*
19+
* @param {string} req - The string to search within.
20+
* @param {string} target - The character to find in the string.
21+
* @returns {number} The index of the first occurrence of the target character,
22+
* or -1 if the target character is not found.
23+
*
24+
* @example
25+
*
26+
* const myString = "Hello, world!";
27+
* const targetChar = "o";
28+
* const index = findFirstBrac(myString, targetChar);
29+
*
30+
* if (index !== -1) {
31+
* console.log(`The first occurrence of '${targetChar}' is at index ${index}.`);
32+
* } else {
33+
* console.log(`The character '${targetChar}' is not found in the string.`);
34+
* }
35+
*/
1636
function findFirstBrac (req, target) {
1737
for (let i = 0; i < req.length; i++) {
1838
if (req[i] === target) {
@@ -23,6 +43,32 @@ function findFirstBrac (req, target) {
2343
}
2444

2545
// POST /api/users HTTP/1.1
46+
/**
47+
* Parses an HTTP request string and extracts its components.
48+
*
49+
* @param {string} request - The HTTP request string to parse.
50+
* @returns {Promise<Object>} A promise that resolves to an object containing the HTTP method, path, version, and body (if applicable).
51+
*
52+
* @example
53+
* // Example HTTP request string
54+
const httpRequest = `POST /api/data HTTP/1.1
55+
Host: example.com
56+
Content-Type: application/json
57+
Content-Length: 51
58+
59+
{
60+
"name": "John Doe",
61+
"email": "john.doe@example.com"
62+
}`;
63+
64+
// Call the httpParser function with the example request
65+
httpParser(httpRequest).then(parsedRequest => {
66+
console.log(parsedRequest);
67+
}).catch(error => {
68+
console.error('Error parsing HTTP request:', error);
69+
});
70+
*
71+
*/
2672
async function httpParser (request) {
2773
const req = new Object()
2874
const requestString = request.split('\n')
@@ -52,6 +98,27 @@ httpParser(request).then((data) => {
5298

5399
})
54100

101+
/**
102+
* Stores a key-value pair from a request string into a JSON object.
103+
*
104+
* @param {Array} req - The request string split into an array of characters.
105+
* @param {Object} httpJSON - The JSON object to store the key-value pair.
106+
* @returns {Array} The modified request array after extracting the key-value pair.
107+
*
108+
* @example
109+
* // Example request string
110+
const requestString = "key1:value1,key2:value2";
111+
const reqArray = requestString.split('');
112+
const httpJSON = {};
113+
114+
// Extract key-value pairs
115+
while (reqArray.length > 0) {
116+
storePair(reqArray, httpJSON);
117+
}
118+
119+
console.log(httpJSON); // Output: { key1: 'value1', key2: 'value2' }
120+
121+
*/
55122
function storePair (req, httpJSON) {
56123
let key = ''
57124
let i = 0
@@ -79,6 +146,18 @@ function storePair (req, httpJSON) {
79146
return req
80147
}
81148

149+
/**
150+
* Parses a JSON body string and converts it into a JSON object.
151+
*
152+
* @param {string} body - The JSON body string to parse.
153+
* @returns {Object} The parsed JSON object.
154+
*
155+
* @example
156+
* const jsonString = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
157+
const parsedObject = JSONbodyParser(jsonString);
158+
console.log(parsedObject); // Output: { key1: 'value1', key2: 'value2' }
159+
160+
*/
82161
function JSONbodyParser (body) {
83162
const req = body.split('')
84163
const httpJSON = new Object()
@@ -105,6 +184,30 @@ function JSONbodyParser (body) {
105184
return httpJSON
106185
}
107186

187+
/**
188+
* Extracts the body of an HTTP request starting from a given position.
189+
*
190+
* @param {Array} req - The request string split into an array of lines.
191+
* @param {number} pos - The position to start extracting the body.
192+
* @returns {Promise<string>} A promise that resolves to the extracted body string.
193+
*
194+
* @example
195+
* const httpRequest = `POST /api/data HTTP/1.1
196+
Host: example.com
197+
Content-Type: application/json
198+
199+
{
200+
"name": "John Doe",
201+
"age": 30
202+
}`;
203+
204+
const requestLines = httpRequest.split('\n');
205+
const bodyStartPos = findFirstBrac(requestLines, '{');
206+
207+
HTTPbody(requestLines, bodyStartPos).then((body) => {
208+
console.log('Extracted Body:', body);
209+
});
210+
*/
108211
function HTTPbody (req, pos) {
109212
flag = 0
110213
let body = ''
@@ -126,6 +229,16 @@ function HTTPbody (req, pos) {
126229
})
127230
}
128231

232+
/**
233+
* Parses a query string from a URL and extracts its components.
234+
*
235+
* @param {string} request - The URL containing the query string.
236+
*
237+
* @example
238+
const url = 'https://example.com?name=JohnDoe&age=25&city=NewYork';
239+
const parsedQuery = queryParser(url);
240+
console.log(parsedQuery); // Output: { name: 'JohnDoe', age: '25', city: 'NewYork' }
241+
*/
129242
function queryParser (request) {
130243
const req = new Object()
131244
const pos = findFirstBrac(request, '?')
@@ -135,6 +248,18 @@ function queryParser (request) {
135248
}
136249
}
137250

251+
/**
252+
* Stores a query string into a JSON object.
253+
*
254+
* @param {string} query - The query string to parse.
255+
* @returns {Object} The parsed query string as a JSON object.
256+
*
257+
* @example
258+
* // Example usage
259+
const queryString = "key1=value1&key2=value2";
260+
const parsedQuery = storeQuery(queryString);
261+
console.log(parsedQuery); // Output: { key1: 'value1', key2: 'value2' }
262+
*/
138263
function storeQuery (query) {
139264
const req = query.split('')
140265
const httpQueryJSON = new Object()
@@ -156,6 +281,24 @@ function storeQuery (query) {
156281
return httpQueryJSON
157282
}
158283

284+
/**
285+
* Stores a key-value pair from a query string into a JSON object.
286+
*
287+
* @param {Array} req - The query string split into an array of characters.
288+
* @returns {Object} The JSON object containing the key-value pair.
289+
*
290+
* @example
291+
* const queryString = "key1=value1&key2=value2";
292+
const queryArray = queryString.split('');
293+
let queryJSON = {};
294+
295+
while (queryArray.length > 0) {
296+
const pair = queryStorePair(queryArray);
297+
queryJSON = { ...queryJSON, ...pair };
298+
}
299+
300+
console.log(queryJSON); // Output: { key1: 'value1', key2: 'value2' }
301+
*/
159302
function queryStorePair (req) {
160303
let key = ''
161304
let i = 0

lib/utils.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
2+
/**
3+
* Finds the index of the first occurrence of the target character in the given string.
4+
* @param {string} req - The string to search through.
5+
* @param {string} target - The character to find in the string.
6+
* @returns {number} The index of the target character or -1 if not found.
7+
*
8+
* @example
9+
* const index = findFirstBrac('Hello, World!', 'o');
10+
*/
111
function findFirstBrac (req, target) {
212
for (let i = 0; i < req.length; i++) {
313
if (req[i] === target) {
@@ -7,6 +17,15 @@ function findFirstBrac (req, target) {
717
return -1
818
}
919

20+
/**
21+
* Parses the HTTP body from a given position.
22+
* @param {string} req - The HTTP request as a string.
23+
* @param {number} pos - The position in the string to start parsing.
24+
* @returns {Promise<string>} A promise that resolves to the cleaned-up body.
25+
*
26+
* @example
27+
* const body = await HTTPbody(req, pos);
28+
*/
1029
function HTTPbody (req, pos) {
1130
let flag = 0
1231
let body = ''
@@ -30,6 +49,14 @@ function HTTPbody (req, pos) {
3049
})
3150
}
3251

52+
/**
53+
* Cleans up the body content by trimming spaces and standardizing spacing around colons and commas.
54+
* @param {string} body - The body content to clean up.
55+
* @returns {string} body - The cleaned-up body.
56+
*
57+
* @example
58+
* const cleanedBody = cleanUpBody(body);
59+
*/
3360
function cleanUpBody (body) {
3461
// Trim leading and trailing spaces
3562
body = body.trim()
@@ -43,6 +70,14 @@ function cleanUpBody (body) {
4370
return body
4471
}
4572

73+
/**
74+
* Parses a JSON-like HTTP body into an object.
75+
* @param {string} body - The HTTP body content as a string.
76+
* @returns {Object} The parsed JSON object.
77+
*
78+
* @example
79+
* const parsedBody = JSONbodyParser(body);
80+
*/
4681
function JSONbodyParser (body) {
4782
const req = body.split('')
4883
const httpJSON = new Object()
@@ -67,6 +102,16 @@ function JSONbodyParser (body) {
67102
return httpJSON
68103
}
69104

105+
106+
/**
107+
* Stores key-value pairs in the provided JSON object.
108+
* @param {Array<string>} req - The remaining request characters.
109+
* @param {Object} httpJSON - The JSON object to store the parsed data.
110+
* @returns {Array<string>} The remaining unprocessed request characters.
111+
*
112+
* @example
113+
* storePair(req, httpJSON);
114+
*/
70115
function storePair (req, httpJSON) {
71116
let key = ''
72117
let value = ''
@@ -100,6 +145,15 @@ function storePair (req, httpJSON) {
100145
return req
101146
}
102147

148+
149+
/**
150+
* Parses primitive values from the request array.
151+
* @param {Array<string>} req - The remaining request characters.
152+
* @returns {string|number} The parsed value, either as a string or number.
153+
*
154+
* @example
155+
* const parsedValue = parseValue(req);
156+
*/
103157
// Helper function to parse primitive values (strings, numbers, etc.)
104158
function parseValue (req) {
105159
let value = ''
@@ -137,6 +191,14 @@ function parseValue (req) {
137191
return isString ? value.trim() : value.trim() // Return the value
138192
}
139193

194+
/**
195+
* Parses a query string from a request URL into a JSON object.
196+
* @param {string} request - The request URL as a string.
197+
* @returns {Object} The parsed query parameters as a JSON object.
198+
*
199+
* @example
200+
* const queryParams = queryParser(request);
201+
*/
140202
function queryParser (request) {
141203
const httpQueryJSON = new Object()
142204
const queryStart = request.indexOf('?')
@@ -159,6 +221,15 @@ function queryParser (request) {
159221

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

224+
225+
/**
226+
* Looks up the MIME type based on the file extension.
227+
* @param {string} extension - The file extension to look up.
228+
* @returns {string} The MIME type or 'application/octet-stream' if not found.
229+
*
230+
* @example
231+
* const mimeType = lookupMimeType('application/json');
232+
*/
162233
function lookupMimeType (extension) {
163234
const mimeType = Object.keys(mimeDb).find(type =>
164235
mimeDb[type].extensions.includes(extension)

0 commit comments

Comments
 (0)