Created
June 8, 2019 17:05
-
-
Save caub/367cf0eeb72ef8706b90ed1ab7c6c62f to your computer and use it in GitHub Desktop.
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 fetch = require('node-fetch'); | |
const http = require('http'); | |
class Express { | |
constructor( | |
notFoundHandler = (req, res) => { | |
res.statusCode = 404; | |
res.write('not found'); | |
res.end() | |
}, | |
errorHandler = (req, res, err = {}) => { | |
if (res.headersSent) { res.end(); return; } | |
res.statusCode = err.status || 500; | |
res.write(err.message || 'error'); | |
res.end() | |
} | |
) { | |
this.stacks = []; | |
this.server = http.createServer(async (req, res) => { | |
try { | |
for (const { method, path, handler } of this.stacks) { | |
if (!method || method === req.method) { | |
const m = req.url.match(path); | |
if (m) { | |
await handler(req, res, m); | |
} | |
} | |
} | |
} catch (err) { | |
console.log('ERR', err); | |
errorHandler(req, res, err); | |
} | |
if (!res.headersSent) { | |
notFoundHandler(req, res); | |
} | |
}); | |
} | |
use(path, handler) { this.stacks.push({ path, handler }) } | |
get(path, handler) { this.stacks.push({ method: 'GET', path, handler }) } | |
put(path, handler) { this.stacks.push({ method: 'PUT', path, handler }) } | |
del(path, handler) { this.stacks.push({ method: 'DELETE', path, handler }) } | |
post(path, handler) { this.stacks.push({ method: 'POST', path, handler }) } | |
patch(path, handler) { this.stacks.push({ method: 'PATCH', path, handler }) } | |
copy(path, handler) { this.stacks.push({ method: 'COPY', path, handler }) } | |
listen(port) { | |
return new Promise((resolve, reject) => this.server.listen(port, err => err ? reject(err) : resolve(this.server))); | |
} | |
close() { | |
return this.server.close(); | |
} | |
} | |
(async () => { | |
try { | |
const app = new Express() | |
app.use(/^\//, async (req, res) => { | |
console.log('just logging stuff', req.url); | |
}); | |
app.get(/^\/foo/, async (req, res) => { | |
res.write('foo'); | |
res.end(); | |
throw new Error('7'); | |
}); | |
app.get(/^\/bar/, async (req, res) => { | |
res.write('bar'); | |
res.end(); | |
}); | |
await app.listen(3000); | |
const r = await fetch('http://localhost:3000/foo'); | |
console.log(1, r.status, await r.text()); | |
app.close(); | |
} catch (err) { | |
console.error(err); | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment