Created
March 27, 2017 08:20
-
-
Save furybean/9a43cbc648b064e0c41ee10037de0645 to your computer and use it in GitHub Desktop.
Koa.js lite
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
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'); | |
}); |
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
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