Fastify系列-从0到1超详细手把手教你使用Fastify构建快速的API

Fastify系列-从0到1超详细手把手教你使用Fastify构建快速的API什么是 Fastify Fastify 是一个 web 框架 高度专注于以最少的开销和强大的插件架构提供**的开发体验 它的灵感来自于 Hapi 和 Express 据我们所知 它是运行在 Node js 上的最快的 Web 框架之一 为什么使用 Fastify 这些是 fasttify 的主要特性和原则 高性能

大家好,我是讯享网,很高兴认识大家。

什么是Fastify?

Fastify是一个web框架,高度专注于以最少的开销和强大的插件架构提供**的开发体验。它的灵感来自于Hapi和Express,据我们所知,它是运行在Node.js上的最快的Web框架之一。

为什么使用Fastify?

这些是fasttify的主要特性和原则

  • 高性能:据我们所知,Fastify是目前最快的web框架之一,根据代码的复杂程度,我们可以每秒处理多达3万个请求。
  • 可扩展:通过钩子、插件和装饰器,fasttify是完全可扩展的。
  • 基于模式:即使不是强制性的,我们也建议使用JSON模式来验证你的路由和序列化你的输出,在内部fasttify会在一个高性能的函数中编译模式。
  • 日志记录:日志非常重要,但成本很高;它拥有最好的日志记录器,不用我们自己手动添加。
  • 对开发人员友好:该框架非常具有表现力,可以在不牺牲性能和安全性的情况下帮助开发人员进行日常使用。
  • TypeScript:支持不断增长的TypeScript

快速上手

  • 官方文档

安装并运行第一个服务

首先,使用命令创建新的Fastify项目
npm i fastify 

讯享网


讯享网

创建server

在项目根目录下创建 app.js 文件

讯享网// CommonJs const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', function (request, reply) { reply.send({ hello: 'world' }) }) // Run the server! fastify.listen({ port: 8081 }, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } console.log(`Server is now listening on ${address}`) }) 

代码表示,监听端口 8081 启动服务器

启动服务

使用 node 命令运行 app.js 文件,如下所示:

node app.js 

测试服务

我们使用浏览器打开http://127.0.0.1:8081/

好了,到此我们已经初步了解了Fastify的基础服务如何搭建与运行,接下来我们进入详细的使用介绍

详细使用

使用async/await

你更喜欢使用async/await吗? Fastify支持开箱即用。

讯享网// ESM import Fastify from 'fastify' const fastify = Fastify({ logger: true }) // CommonJs const fastify = require('fastify')({ logger: true }) fastify.get('/', async (request, reply) => { return { hello: 'world' } }) / * Run the server! */ const start = async () => { try { await fastify.listen({ port: 3000 }) } catch (err) { fastify.log.error(err) process.exit(1) } } start() 

开始我们的第一个插件-路由

  • 在JavaScript中一切都是对象,而在fasttify中一切都是插件。
  • 我们接下来要声明一个路由文件,我们需要把它单独抽离出来,放在入口的外面。
  • 查看路由声明文档:https://www.fastify.cn/docs/latest/Reference/Routes/
创建路由文件

在根目录下创建 route.js

/ * Encapsulates the routes * @param {FastifyInstance} fastify Encapsulated Fastify Instance * @param {Object} options plugin options, refer to https://www.fastify.io/docs/latest/Reference/Plugins/#plugin-options */ async function routes (fastify, options) { fastify.get('/', async (request, reply) => { return { hello: 'world' } }) } module.exports = routes 
注册路由文件

修改app.js

讯享网// fastify.get('/', async (request, reply) => { // return { hello: 'world' } // }) 

改为

fastify.register(require('./route')) 

启动、测试服务

使用 node 命令运行

讯享网node app.js 


我们使用浏览器打开http://127.0.0.1:8081/

至此,我们的路由已经创建完毕,是不是很简单呢?大家可以观察到,Fasttify提供了async await 来实现接口调用,这一点十分重要,因为当我们链接数据库的时候,需要保证数据库是可用状态后才可以去读取数据,这个时候就需要用到async了,接下来我们一起来试试吧

数据库连接

我们以postgres数据库为例

前置条件

我们需要一个db url 创建好的db数据库可以用来使用哦~~

安装依赖
npm i fastify-plugin npm i pg @fastify/postgres 

相关文档
https://www.npmjs.com/package/@fastify/postgres
https://www.fastify.cn/docs/latest/Guides/Getting-Started/

编写插件

根目录下创建postgres-connector.js

讯享网/ * @type {import('fastify-plugin').FastifyPlugin} */ const fastifyPlugin = require('fastify-plugin') / * Connects to a postgres database * @param {FastifyInstance} fastify Encapsulated Fastify Instance * @param {Object} options plugin options, refer to https://www.fastify.io/docs/latest/Reference/Plugins/#plugin-options */ async function dbConnector (fastify, options) { fastify.register(require('@fastify/postgres'), { connectionString: 'postgresql://名字:密码@数据库服务器名:端口号/数据库名' }) } // Wrapping a plugin function with fastify-plugin exposes the decorators // and hooks, declared inside the plugin to the parent scope. module.exports = fastifyPlugin(dbConnector) 
注册插件

打开app.js 注册我们写的插件

fastify.register(require('./postgres-connector')) 

添加测试接口

打开route.js,添加测试接口代码

讯享网/ * Encapsulates the routes * @param {FastifyInstance} fastify Encapsulated Fastify Instance * @param {Object} options plugin options, refer to https://www.fastify.io/docs/latest/Reference/Plugins/#plugin-options */ async function routes(fastify, options) { fastify.get("/", async (request, reply) => { return { hello: "world" }; }); fastify.get("/test", async (req, reply) => { const client = await fastify.pg.connect(); try { const { rows } = await client.query("SELECT id, name FROM tests"); // Note: avoid doing expensive computation here, this will block releasing the client return rows; } finally { // Release the client immediately after query resolves, or upon error client.release(); } }); } module.exports = routes; 

启动服务测试
node app.js 
成功获取数据库信息

总结
  • 如上图所见,我们对数据库连接器和路由的注册都使用了register。
  • 这是Fastify最好的特性之一,它会按照你声明插件的顺序加载插件,并且只在当前插件被加载后才会加载下一个插件。
  • 通过这种方式,我们可以在第一个插件中注册数据库连接器,并在第二个插件中使用它
  • 请阅读此处以了解如何处理插件的作用域:https://www.fastify.cn/docs/latest/Reference/Plugins/#handle-the-scope
  • 当你调用fastify.listen()、fastify.inject()或fastify时,插件加载开始。
  • postgres插件使用装饰API将自定义对象添加到fasttify实例,官方文档鼓励使用这种api来简化代码重用并减少代码或逻辑重复。
  • 要深入了解fasttify插件是如何工作的,如何开发新的插件,以及如何使用整个fasttify API来处理异步启动应用程序的复杂性的细节,请阅读插件指南
  • 今天就写到这里啦~
  • 小伙伴们,( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ我们明天再见啦~~
  • 大家要天天开心哦

在这里插入图片描述

欢迎路过的小哥哥小姐姐们提出更好的意见哇~~
小讯
上一篇 2025-03-22 14:54
下一篇 2025-03-19 20:32

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/99218.html