美文网首页nodeJs
Fastify系列【使用初步】

Fastify系列【使用初步】

作者: 老鱼_chaimyu | 来源:发表于2019-05-11 11:03 被阅读0次

本文仅用来记录个人使用过程备忘

安装

建立项目,并安装fastify

Chaim:examp1 Chaim$ npm init
Chaim:examp1 Chaim$ npm install fastify --save

server.js

// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })

// Declare a route
fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

// Run the server!
const start = async () => {
  try {
    await fastify.listen(3000)
    fastify.log.info(`server listening on ${fastify.server.address().port}`)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

启动服务

Chaim:examp1 Chaim$ node server
{"level":30,"time":1557508003756,"pid":3401,"hostname":"Chaim.local","msg":"Server listening at http://127.0.0.1:3000","v":1}
{"level":30,"time":1557508003756,"pid":3401,"hostname":"Chaim.local","msg":"server listening on 3000","v":1}

看起来在3000端口监听了,浏览器打开"http://127.0.0.1:3000/" ,可以看到返回信息

{"hello":"world"}

日志功能默认是关闭的,测试例子中已经打开日志功能,如下:

const fastify = require('fastify')({
  logger: true
})

路由

类似以下方式注册一个路由

fastify.route({
  method: 'POST',
  url: '/api/log/jsons',
  handler: (req, res) => {
    req.body.on('data', d => console.log(d)) // log every incoming object
  }
})

method

支持的method:'DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT' 和 'OPTIONS'。

url

url支持格式:https://github.com/delvedor/find-my-way#supported-path-formats

schema

一个包含请求和响应模式的对象。

需要符合 JSON Schema 的格式。

        schema: {
          description: '管理员登录',
          tags: ['admin'],
          body: {
           type: 'object',
           properties: {
             username: { type: 'string' },
             password: { type: 'string' },
           }
          }

注意:Fastify 只支持 application/json 内容类型,如果想解析其他类型可以查看社区插件,fastify-formbody 可以解析 x-www-form-urlencoded 请求类型,使用 fastify-multipart 处理 form-data 类型请求。或者使用 ContentTypeParser 方法自定义内容类型解析器。

Express/Restify

fastify 支持类似 Express/Restify 的路由语法:

  • fastify.get(path, [options], handler)
  • fastify.head(path, [options], handler)
  • fastify.post(path, [options], handler)
  • fastify.put(path, [options], handler)
  • fastify.delete(path, [options], handler)
  • fastify.options(path, [options], handler)
  • fastify.patch(path, [options], handler)
  • fastify.all(path, [options], handler)

如下

    fastify.post('/login', {
        schema: {
          description: '管理员登录',
          tags: ['admin'],
          body: {
           type: 'object',
           properties: {
             username: { type: 'string' },
             password: { type: 'string' },
           }
          }
        }
    }, login);

生命周期

这个整理的图不错,很清晰表达了整个过程,抄录下

Incoming Request (请求到达)
  │
  └─▶ Instance Logger (实例化 Logger)
        │
        └─▶ Routing (路由匹配)
             │
       404 ◀─┴─▶ onRequest Hook (onRequest钩子)
                  │
        4**/5** ◀─┴─▶ run Middlewares (执行中间件)
                        │
              4**/5** ◀─┴─▶ Parsing (解析请求对象)
                             │
                       415 ◀─┴─▶ Validation (验证)
                                   │
                             400 ◀─┴─▶ preHandler Hook (preHandler钩子)
                                         │
                               4**/5** ◀─┴─▶ beforeHandler
                                               │
                                     4**/5** ◀─┴─▶ User Handler
                                                     │
                                                     └─▶ Reply (响应)
                                                          │ │
                                                          │ └─▶ Outgoing Response (发出响应)
                                                          │
                                                          └─▶ onResponse Hook (onResponese钩子

参考

https://www.fastify.io

https://www.fastify.io/ecosystem/

介绍fastify不错的文章
http://lavyun.cn/blog/20171029-Fastify,node

相关文章

网友评论

    本文标题:Fastify系列【使用初步】

    本文链接:https://www.haomeiwen.com/subject/cgxxaqtx.html