Skip to content

Instantly share code, notes, and snippets.

@luxiaojian
Forked from furybean/example.js
Created March 27, 2017 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luxiaojian/92f35c51d7658c772ca8318f953f4224 to your computer and use it in GitHub Desktop.
Save luxiaojian/92f35c51d7658c772ca8318f953f4224 to your computer and use it in GitHub Desktop.
Koa.js lite
const Koa = require('./koa');
const app = new Koa();
// logger
app.use(async function (ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(8888, function() {
console.log('listen at 8888');
});
const invokeMiddlewares = async function(context, fns) {
const length = fns.length;
let current = 0;
const next = function() {
return new Promise((resolve, reject) => {
const fn = fns[current++];
if (current > length) return resolve();
try {
resolve(fn(context, next));
} catch(error) {
reject(error);
}
});
};
return next();
};
module.exports = class Koa {
constructor() {
this.middlewares = [];
this.server = null;
}
use(fn) {
this.middlewares.push(fn);
}
createContext(req, res) {
const ctx = {
body: null,
method: req.method,
url: req.url,
req,
res
};
return ctx;
}
async handleRequest(req, res) {
const context = this.createContext(req, res);
await invokeMiddlewares(context, this.middlewares);
let body = context.body;
if (typeof body === 'string') {
return res.end(body);
}
body = JSON.stringify(body);
res.end(body);
}
listen(port, callback) {
const http = require('http');
const server = this.server = http.createServer((req, res) => {
this.handleRequest(req, res);
});
server.listen(port, callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment