import Server from "./server";
const PORT = 5000;
const server = new Server();
server.route.register("/", (req, res) => {
res.end("ok");
});
server.listen(PORT, () => console.log(`Server listening on ${PORT}`));
Created
June 22, 2018 04:18
-
-
Save m8r1x/9c1399ff37ed043734deaffd093b1d04 to your computer and use it in GitHub Desktop.
Nodejs Server with vanilla nodejs + typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ServerRequest, ServerResponse } from "http"; | |
type HandlerFunction = (request: ServerRequest, response: ServerResponse) => void; | |
class Handler { | |
public process: HandlerFunction; | |
constructor(method: HandlerFunction) { | |
this.method = method; | |
} | |
process(req: ServerRequest, res: ServerResponse) { | |
let params = null; | |
return this.method.apply(this, [req, res, params]); | |
} | |
} | |
export default Handler; | |
export HandlerFunction; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { parse } = require("url"); | |
import Handler, { HandlerFunction } from "./handler"; | |
interface IHandlerStore { | |
[key:string]: Handler | |
} | |
class Router { | |
public handlers: IHandlerStore = {}; | |
clear() { | |
this.handlers = {}; | |
} | |
register(url: string, method: HandlerFunction) { | |
this.handlers[url] = new Handler(method); | |
} | |
route(req) { | |
const url = parse(req.url, true); | |
let handler = this.handlers[url.pathname]; | |
return handler || this.missing(); | |
} | |
missing() { | |
return new Handler((req: ServerRequest, res: ServerResponse) => { | |
res.writeHead(404); | |
res.end(`${req.url} not found`); | |
}); | |
} | |
} | |
export default Router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createServer } from "http"; | |
import Router from "./router"; | |
class Server { | |
public router = new Router(); | |
listen(...args) { | |
const internalServer = createServer((req, res) => { | |
const routeHandler = this.router.route(req); | |
routeHandler.process(req, res); | |
}); | |
return internalServer.listen(...args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment