超详细手把手教你使用Fastify构建快速的API

发布时间 2023-07-25 19:25:15作者: 糖~豆豆

什么是

快速上手

安装并运行第一个服务

首先,使用命令创建新的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

成功获取数据库信息