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

什么是Fastify?

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

为什么使用Fastify?

fasttify的主要特性和原则

  • 高性能:据我们所知,Fastify是目前最快的web框架之一,根据代码的复杂程度,我们可以每秒处理多达3万个请求。

  • 可扩展:通过钩子、插件和装饰器,fasttify是完全可扩展的。

  • 基于模式:即使不是强制性的,我们也建议使用JSON模式来验证你的路由和序列化你的输出,在内部fasttify会在一个高性能的函数中编译模式。

  • 日志记录:日志非常重要,但成本很高;它拥有最好的日志记录器,不用我们自己手动添加。

  • 对开发人员友好:该框架非常具有表现力,可以在不牺牲性能和安全性的情况下帮助开发人员进行日常使用。

  • TypeScript:支持不断增长的TypeScript

快速上手

安装并运行第一个服务

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

css 复制代码
npm i fastify

创建server

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

javascript 复制代码
// 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支持开箱即用。

javascript 复制代码
// 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中一切都是插件。
  • 我们接下来要声明一个路由文件,我们需要把它单独抽离出来,放在入口的外面。
  • 查看路由声明文档:www.fastify.cn/docs/latest...

创建路由文件

在根目录下创建 route.js

javascript 复制代码
/**
 * 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

perl 复制代码
// fastify.get('/', async (request, reply) => {
//   return { hello: 'world' }
// })

改为

c 复制代码
fastify.register(require('./route'))

启动、测试服务

使用 node 命令运行

复制代码
node app.js

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

数据库连接

我们以postgres数据库为例

前置条件

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

安装依赖

css 复制代码
npm i fastify-plugin 
npm i pg @fastify/postgres

相关文档

www.npmjs.com/package/@fa... www.fastify.cn/docs/latest...

编写插件

根目录下创建postgres-connector.js

php 复制代码
/**
 * @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 注册我们写的插件

c 复制代码
fastify.register(require('./postgres-connector'))

添加测试接口

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

javascript 复制代码
/**
 * 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最好的特性之一,它会按照你声明插件的顺序加载插件,并且只在当前插件被加载后才会加载下一个插件。

  • 通过这种方式,我们可以在第一个插件中注册数据库连接器,并在第二个插件中使用它

  • 请阅读此处以了解如何处理插件的作用域:www.fastify.cn/docs/latest...

  • 当你调用fastify.listen()、fastify.inject()或fastify时,插件就开始加载了哦。

  • postgres插件使用装饰API将自定义对象添加到fasttify实例,官方文档鼓励使用这种api来简化代码重用并减少代码或逻辑重复。

  • 要深入了解fasttify插件是如何工作的,如何开发新的插件,以及如何使用整个fasttify API来处理异步启动应用程序的复杂性的细节,请阅读插件指南

  • 今天就写到这里啦~明天晚上继续写哦

  • 小伙伴们,( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ我们明天再见啦~~

  • 大家要天天开心哦

欢迎大家指出文章需要改正之处~

学无止境,合作共赢

欢迎路过的小哥哥小姐姐们提出更好的意见哇~~

相关推荐
To_OC2 小时前
别再串行写 await 了,Promise.all 才是并行请求的正确打开方式
前端·javascript·promise
To_OC3 小时前
LC 17 电话号码的字母组合:我的回溯算法,就是从这道题开窍的
javascript·算法·leetcode
vipbic3 小时前
中后台越做越乱后,我用插件化把它救回来了
前端·vue.js
Hyyy3 小时前
Computer Use 适合做什么,不适合做什么——一次真实使用后的思考
前端
小和尚同志3 小时前
前端 AI 单元测试思考与落地
前端·人工智能·aigc
invicinble4 小时前
c端系统,其实更像一个信息展示平台
前端
你怎么知道我是队长5 小时前
JavaScript的变量和数据类型介绍
开发语言·javascript·ecmascript
李姆斯5 小时前
管理是否可以被完全量化
前端·产品经理·团队管理
戮漠summer6 小时前
Missing Semester 计算机教育中缺失的一课 Lecture 01 Shell
开发语言·后端·scala
名字还没想好☜6 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js