Skip to content

Instantly share code, notes, and snippets.

@andreciornavei
Created May 14, 2022 17:23
Show Gist options
  • Save andreciornavei/923e69c27b41f4804c66d81573f9e0e8 to your computer and use it in GitHub Desktop.
Save andreciornavei/923e69c27b41f4804c66d81573f9e0e8 to your computer and use it in GitHub Desktop.
NodeJS http ROUTE RESOLVER
import * as http from "http"
const PORT = 1337
type Request = http.IncomingMessage & {
params?: Map<String, String>
}
const routeResolver = async (routes: Map<string, Function> = new Map(), req: http.IncomingMessage, res: http.ServerResponse) => {
const requestPaths: string[] = req.url.split("/").filter(path => path.length > 0)
routeLoop: for (const route of Array.from(routes.keys())) {
const [method, url] = route.split(" ")
const paths: string[] = url.split("/").filter(path => path.length > 0)
// continue to next loop if methods not matches
if (method !== req.method)
continue routeLoop
// return selected method if it does not contains params and urls has exacly matches
if (!paths.some(path => path.startsWith(":")) && url === req.url)
return routes.get(route)(req, res)
// if paths has the same length and non params matches
// collect all params and call route function
if (paths.length === requestPaths.length) {
const params: Map<string, string> = new Map()
for (let i = 0; i < paths.length; i++) {
if (paths[i].startsWith(":")) params.set(String(paths[i]).slice(1), requestPaths[i])
else if (paths[i] !== requestPaths[i]) continue routeLoop
}
return routes.get(route)({ ...Object.create(req), params: params }, res)
}
}
res.writeHead(404, "Not Found", { "Content-Type": "text/json" })
return res.end(JSON.stringify({ message: "Resource notfound" }))
}
const app = http.createServer((req: http.IncomingMessage, res: http.ServerResponse) => {
const routes: Map<string, Function> = new Map()
routes.set("GET /products/all", (request: Request, response) => {
return response.end(JSON.stringify({ message: "getting all product" }))
})
routes.set("GET /products/:id", (request: Request, response) => {
return response.end(JSON.stringify({ message: `getting product with id = ${request.params.get("id")}` }))
})
return routeResolver(routes, req, res)
})
app.listen(PORT)
app.on("listening", () => console.log(`server listening on port ${PORT}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment