Skip to content

Instantly share code, notes, and snippets.

@m8r1x
Created June 22, 2018 04:18
Show Gist options
  • Save m8r1x/9c1399ff37ed043734deaffd093b1d04 to your computer and use it in GitHub Desktop.
Save m8r1x/9c1399ff37ed043734deaffd093b1d04 to your computer and use it in GitHub Desktop.
Nodejs Server with vanilla nodejs + typescript

Usage

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}`));
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;
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;
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