hey gusys so im a intermediate dev , im building my own expressjs & fastify type web server library.
but my bottleneck is that my library has to wait for full req to come then parse it by using another func.but i want to parse it by chunks
let me explain like – as data comes in chunk to my lib so it should not wait for full req rather it should parse that req immediately and as data come in chunks it should parse , so by this algo my library doesn’t have to wait.
here is code –
import net from "net";
import ResponseHandler from "./responseHandler.js";
import { createConnectionHandler } from "./handleConnection.js";
import Trie from "./trie.js";
class Maya {
constructor() {
this.routes = {
GET: {},
POST: {},
PUT: {},
DELETE: {},
};
this.middlewares = {};
this.ResponseHandler = ResponseHandler;
this.isBodyParse = false;
this.compiledMiddlewares = [];
this.compiledRoutes = {};
}
compile() {
// console.log("Compiling middlewares and routes...");
// Preprocess middlewares
this.compiledMiddlewares = Object.entries(this.middlewares).sort(([a], [b]) => b.length - a.length);
// console.log("Compiled middlewares:", this.compiledMiddlewares);
// Preprocess routes by method
for (const method in this.routes) {
this.compiledRoutes[method] = Object.entries(this.routes[method])
.sort(([a], [b]) => b.length - a.length);
}
}
listen(port = 3000, callback) {
this.compile();
const handleConnection = createConnectionHandler(this, this.isBodyParse);
const server = net.createServer((socket) => handleConnection(socket));
server.listen(port, () => {
if (typeof callback === "function") {
return callback();
}
});
}
use(pathORhandler, handler) {
if (typeof pathORhandler === "string") {
this.middlewares[pathORhandler] = handler;
} else {
this.middlewares["/"] = pathORhandler;
}
}
bodyParse() {
this.isBodyParse = true;
}
get(path, handler) {
this.routes.GET[path] = handler;
}
post(path, handler) {
this.routes.POST[path] = handler;
}
put(path, handler) {
this.routes.PUT[path] = handler;
}
delete(path, handler) {
this.routes.DELETE[path] = handler;
}
}
export default Maya;
// this is req parser
import Cache from "./cache.js";
export function parseRequest(requestBuffer) {
const cache = new Cache();
// console.log(requestBuffer)
const req = requestBuffer.toString()
// console.log(requestBuffer)
// Split headers and body
const [headerSection, body] = req.split("rnrn", 2);
if (!headerSection) {
return error({ error: "Invalid request format: Missing header section" });
}
// spit headers into two line
const [requestLine, ...headerLine] = headerSection.split("rn");
if (!requestLine) {
return error({ error: "Invalid request format: Missing request line" });
}
// parse request line
const [method, path, version] = requestLine.split(" ");
if (!method || !path || !version) {
return error({ error: "Invalid request format: Incomplete request line" });
}
const [url, queryString] = path.split("?", 2);
const queryParams = new URLSearchParams(queryString);
// generate cache key
const cacheKey = `${method}:${url}?${queryString}:${JSON.stringify(headerLine)}`;
if (method === "GET") {
const cachedResponse = cache.getCached(cacheKey);
if (cachedResponse) {
return cachedResponse;
}
}
// parse headers and cookie
const headers = {};
const Cookies = {};
for (const line of headerLine) {
const [key, value] = line.split(": ");
headers[key.toLowerCase()] = value;
if (key.toLowerCase() === "cookie") {
value.split(";").forEach((cookie) => {
const [Cookiekey, Cookievalue] = cookie.trim().split("=");
Cookies[Cookiekey] = decodeURIComponent(Cookievalue);
});
}
}
let parsedBody;
const contentType = headers["content-type"];
if (body) {
if (contentType === "application/json") {
try {
parsedBody = JSON.parse(body);
} catch (error) {
return { error: "Invalid JSON format" };
}
} else if (contentType === "application/x-www-form-urlencoded") {
parsedBody = Object.fromEntries(new URLSearchParams(body));
} else {
parsedBody = body;
}
}
const queryParamsObject = {};
for (const [key, value] of queryParams.entries()) {
queryParamsObject[key] = value;
}
const res = {
method,
path: decodeURIComponent(path),
version,
headers,
body: parsedBody,
query: queryParams,
Cookies,
};
if (method === "GET") {
cache.setCache(cacheKey, res);
}
return res;
}
i tried to solve my problem but i couldnt
pradeep kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.