Skip to content

Instantly share code, notes, and snippets.

@tadjik1
Created March 27, 2017 16:19
Show Gist options
  • Save tadjik1/ac64fcf7289e01d525b77669f10663a0 to your computer and use it in GitHub Desktop.
Save tadjik1/ac64fcf7289e01d525b77669f10663a0 to your computer and use it in GitHub Desktop.
simple koajs implementation
const {Server} = require('http');
class KoaError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
module.exports = class Koa {
constructor() {
this._server = null;
this._handlers = [];
}
_handler(req, res) {
// context will share between all middlewares
const ctx = {
req, res, body: undefined,
throw(status, message) { throw new KoaError(status, message); }
};
const callMiddleware = (index) => {
const middleware = this._handlers[index];
// last or single
if (index === this._handlers.length || !middleware) return Promise.resolve();
return Promise.resolve(middleware(ctx, () => {
return callMiddlware(index + 1);
}));
}
callMiddleware(0)
.then(() => {
if (!ctx.body) {
res.statusCode = 404;
res.end("Not found");
} else {
res.end(ctx.body.toString());
}
})
.catch(err => {
if (err.status) {
res.statusCode = err.status;
res.end(err.message.toString());
} else {
throw err;
}
});
}
/*
middleware - async function, that received ctx and next parameters
ctx - object that contains req and res
next - next function in chain
*/
use(middleware) {
this._handlers.push(middleware);
}
listen(port) {
if (this._server) throw new Error('Server already exists');
this._server = new Server(this._handler.bind(this));
this._server.listen(port);
}
close() {
if (!this._server) throw new Error('Server does not exist');
this._server.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment