|
| 1 | +const http = require("node:http"); |
| 2 | + |
| 3 | +const PORT = 5255; |
| 4 | + |
| 5 | +const HTTP_METHODS = { |
| 6 | + GET: "GET", |
| 7 | + POST: "POST", |
| 8 | + PUT: "PUT", |
| 9 | + DELETE: "DELETE", |
| 10 | + PATCH: "PATCH", |
| 11 | + HEAD: "HEAD", |
| 12 | + OPTIONS: "OPTIONS", |
| 13 | + CONNECT: "CONNECT", |
| 14 | + TRACE: "TRACE", |
| 15 | +}; |
| 16 | + |
| 17 | +class Router { |
| 18 | + constructor() { |
| 19 | + this.routes = {}; |
| 20 | + } |
| 21 | + |
| 22 | + #addRoute(method, path, handler) { |
| 23 | + if (typeof path !== "string" || typeof handler !== "function") { |
| 24 | + throw new Error("Invalid argument types: path must be a string and handler must be a function"); |
| 25 | + } |
| 26 | + this.routes[`${method} ${path}`] = handler; |
| 27 | + } |
| 28 | + |
| 29 | + handleRequest(request, response) { |
| 30 | + const { url, method } = request; |
| 31 | + const handler = this.routes[`${method} ${url}`]; |
| 32 | + |
| 33 | + if (!handler) { |
| 34 | + return console.log("404 Not found"); |
| 35 | + } |
| 36 | + |
| 37 | + handler(request, response); |
| 38 | + } |
| 39 | + |
| 40 | + get(path, handler) { |
| 41 | + this.#addRoute(HTTP_METHODS.GET, path, handler); |
| 42 | + } |
| 43 | + |
| 44 | + post(path, handler) { |
| 45 | + this.#addRoute(HTTP_METHODS.POST, path, handler); |
| 46 | + } |
| 47 | + |
| 48 | + put(path, handler) { |
| 49 | + this.#addRoute(HTTP_METHODS.PUT, path, handler); |
| 50 | + } |
| 51 | + |
| 52 | + delete(path, handler) { |
| 53 | + this.#addRoute(HTTP_METHODS.DELETE, path, handler); |
| 54 | + } |
| 55 | + |
| 56 | + patch(path, handler) { |
| 57 | + this.#addRoute(HTTP_METHODS.PATCH, path, handler); |
| 58 | + } |
| 59 | + |
| 60 | + head(path, handler) { |
| 61 | + this.#addRoute(HTTP_METHODS.HEAD, path, handler); |
| 62 | + } |
| 63 | + |
| 64 | + options(path, handler) { |
| 65 | + this.#addRoute(HTTP_METHODS.OPTIONS, path, handler); |
| 66 | + } |
| 67 | + |
| 68 | + connect(path, handler) { |
| 69 | + this.#addRoute(HTTP_METHODS.CONNECT, path, handler); |
| 70 | + } |
| 71 | + |
| 72 | + trace(path, handler) { |
| 73 | + this.#addRoute(HTTP_METHODS.TRACE, path, handler); |
| 74 | + } |
| 75 | + |
| 76 | + printRoutes() { |
| 77 | + console.log(Object.entries(this.routes)); |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +const router = new Router(); |
| 82 | + |
| 83 | +router.get("/", function handleGetBasePath(req, res) { |
| 84 | + console.log("Hello from GET /"); |
| 85 | + res.end(); |
| 86 | +}); |
| 87 | + |
| 88 | +router.post("/", function handlePostBasePath(req, res) { |
| 89 | + console.log("Hello from POST /"); |
| 90 | + res.end(); |
| 91 | +}); |
| 92 | + |
| 93 | +// Note: We're using an arrow function instead of a regular function now |
| 94 | +let server = http.createServer((req, res) => router.handleRequest(req, res)); |
| 95 | +server.listen(PORT); |
0 commit comments