项目作者: nicolasparada

项目描述 :
HTTP tools for Node.js
高级语言: JavaScript
项目地址: git://github.com/nicolasparada/node-httptools.git
创建时间: 2018-04-15T03:06:17Z
项目社区:https://github.com/nicolasparada/node-httptools

开源协议:ISC License

下载


@nicolasparada/httptools"">@nicolasparada/httptools

This package provides some utilities to complement Node’s HTTP server.

Shipped like an ES module.
Enable support with --experimental-modules and Node.js >= v12.0.0.

Routing

  1. import { createServer } from 'http'
  2. import { createRouter } from '@nicolasparada/httptools'
  3. const router = createRouter()
  4. router.handle('GET', '/', (req, res) => {
  5. res.end('Hello there 🙂')
  6. })
  7. const server = createServer(router.handler)
  8. server.listen(3000, '127.0.0.1', () => {
  9. console.log('Server running at http://localhost:3000 🚀')
  10. })

You can register HTTP handlers for a given HTTP verb and URL pattern.

Pattern Matching and Context

  1. import { contextFor, pattern } from '@nicolasparada/httptools'
  2. router.handle('GET', pattern`/hello/{name}`, (req, res) => {
  3. const ctx = contextFor(req)
  4. const params = ctx.get('params')
  5. res.end(`Hello, ${params.name}!`)
  6. })

You can create dynamic routes by passing a regular expression. pattern() is a tagged template literal function that converts the given pattern into a regular expression for simplicity. In this example, it’s equivalent to /^\/hello\/(?<name>[^\/]+)$/.

You can capture parameters from the URL with a curly braces syntax as shown there. You can also use a wilcard * to capture anything.

Inside the request context, you’ll find a “params” object with all the URL parameters.
Context can be filled with your own data. See middleware down below. I do that to not mess with the Node.js API.

Middleware

  1. router.handle('GET', '/auth_user', withAuthUser(authUserHandler))
  2. function withAuthUser(next) {
  3. return (req, res) => {
  4. const token = extractToken(req)
  5. const authUser = decodeToken(token)
  6. const ctx = contextFor(req)
  7. ctx.set('auth_user', authUser)
  8. return next(req, res)
  9. }
  10. }
  11. function authUserHandler(req, res) {
  12. const ctx = contextFor(req)
  13. const authUser = ctx.get('auth_user')
  14. res.setHeader('Content-Type', 'application/json; charset=utf-8')
  15. res.end(JSON.stringify(authUser))
  16. }

contextFor() will give you a WeakMap in which you can save data scoped to the request.
Just use function composition for middleware.

Sub-routing

  1. import { createRouter, pattern, stripPrefix } from '@nicolasparada/httptools'
  2. const api = createRouter()
  3. api.handle('GET', '/', handler)
  4. const router = createRouter()
  5. router.handle('*', pattern`/api/*`, stripPrefix('/api', api.handler))

stripPrefix() is a middleware that trims the given prefix from the request URL. That way, you can compose multiple routers.