项目作者: intrnl

项目描述 :
A lightweight HTTP web framework
高级语言: TypeScript
项目地址: git://github.com/intrnl/srv.git
创建时间: 2021-01-02T16:22:10Z
项目社区:https://github.com/intrnl/srv

开源协议:MIT License

下载


Srv

A lightweight HTTP web framework.

Usage

Uses ES Modules, requires Node v14.13.0+

For TypeScript users: Be sure to install @types/node for Node.js typings

  1. npm install @intrnl/srv
  2. # pnpm install @intrnl/srv
  3. # yarn add @intrnl/srv
  1. import * as http from 'http';
  2. import { Application } from '@intrnl/srv';
  3. let app = new Application();
  4. app.use(({ request, response }) => {
  5. response.body = 'Hello, world!';
  6. });
  7. http.createServer(app.handler).listen(1234);

Middlewares

An Srv application is essentially a chain of middlewares; like a middleman, they
are functions that runs in between receiving and responding to a request, and
they can run code before and after the next one

  1. // Logger
  2. app.use(({ request }, next) => {
  3. console.log(`-> Received ${request.method} on ${request.url.path}`);
  4. return next();
  5. });
  6. // Response time
  7. app.use(async ({ response }, next) => {
  8. let start = Date.now();
  9. await next();
  10. let end = Date.now();
  11. response.headers.set('x-response-time', end - start);
  12. });
  13. // Response
  14. app.use(({ response }) => {
  15. response.body = 'Hello, world!';
  16. });

Middlewares must return or await when trying to call the next one, or you
will stop the chain early before the next middleware is able to handle the
request, causing race conditions and unhandled promise rejections

  1. app.use((ctx, next) => {
  2. // you return it like so
  3. return next();
  4. });
  5. app.use(async (ctx, next) => {
  6. // or await, if you need to run something after the next middleware
  7. await next();
  8. });