本文僅用來記錄個(gè)人使用過程備忘
安裝
建立項(xiàng)目牲尺,并安裝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()
啟動(dòng)服務(wù)
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端口監(jiān)聽了地来,瀏覽器打開"http://127.0.0.1:3000/" 戳玫,可以看到返回信息
{"hello":"world"}
日志功能默認(rèn)是關(guān)閉的,測(cè)試?yán)又幸呀?jīng)打開日志功能未斑,如下:
const fastify = require('fastify')({
logger: true
})
路由
類似以下方式注冊(cè)一個(gè)路由
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
一個(gè)包含請(qǐng)求和響應(yīng)模式的對(duì)象。
需要符合 JSON Schema 的格式蜡秽。
schema: {
description: '管理員登錄',
tags: ['admin'],
body: {
type: 'object',
properties: {
username: { type: 'string' },
password: { type: 'string' },
}
}
注意:Fastify 只支持 application/json 內(nèi)容類型府阀,如果想解析其他類型可以查看社區(qū)插件,fastify-formbody 可以解析 x-www-form-urlencoded 請(qǐng)求類型芽突,使用 fastify-multipart 處理 form-data 類型請(qǐng)求试浙。或者使用 ContentTypeParser 方法自定義內(nèi)容類型解析器寞蚌。
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);
生命周期
這個(gè)整理的圖不錯(cuò)田巴,很清晰表達(dá)了整個(gè)過程,抄錄下
Incoming Request (請(qǐng)求到達(dá))
│
└─? Instance Logger (實(shí)例化 Logger)
│
└─? Routing (路由匹配)
│
404 ?─┴─? onRequest Hook (onRequest鉤子)
│
4**/5** ?─┴─? run Middlewares (執(zhí)行中間件)
│
4**/5** ?─┴─? Parsing (解析請(qǐng)求對(duì)象)
│
415 ?─┴─? Validation (驗(yàn)證)
│
400 ?─┴─? preHandler Hook (preHandler鉤子)
│
4**/5** ?─┴─? beforeHandler
│
4**/5** ?─┴─? User Handler
│
└─? Reply (響應(yīng))
│ │
│ └─? Outgoing Response (發(fā)出響應(yīng))
│
└─? onResponse Hook (onResponese鉤子
參考
https://www.fastify.io/ecosystem/
介紹fastify不錯(cuò)的文章
http://lavyun.cn/blog/20171029-Fastify,node