神刀安全网

Pure fun(ction) HTTP server in Node.js, written in TypeScript

:monkey_face: Fun(ctional) Http

HTTP server should be as stateless as possible like functions. We should write request handlers in pure funtion. Let’s treat return value as responses and use promises to wrap async operations.

Usage

fun-httpsupports Node >= 4.

npm install --save fun-http
const FunHttp = require('../').FunHttp; const app = new FunHttp();  app.use(function (req) {   return 'Hello, World!'; });  app.listen(3000, () => {   console.log('server started'); });

Visit localhost:3000 will display "Hello, World!".

You can also return promise in request handlers, the resolved value will become the body of response.

app.use(function (req) {   return Promise.resolve('Hello, World!'); });

If returned value (or promise resolved value) is not a number of string, it will be parsed into JSON string using JSON.stringify .

Middleware

fun-httpsupports middleware similar to Koa. Calling next will invoke next middleware and return a promise wrapping the return value of that middleware.

app.use(function (req, next) {   return next()     .then(name => {       return {hello: name}; // name === 'World'     }); });  app.use(function () {   return 'World'; });

Paire with co , you can make everything cleaner.

const co = require('co');  app.use(co(function *(req, next) {   const name = yield next();   return {hello: name}; }));  app.use(function () {   return 'World'; });

Examples

Check outexamples.

TypeScript

Did I tell you fun-http is written using TypeScript ?

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Pure fun(ction) HTTP server in Node.js, written in TypeScript

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址