【Node.js】使用fastify搭建一个web服务

前言

目前使用node.js搭建web服务,可以使用原生的http模块进行搭建,也有express、restify和fastify。fastify框架相对于前两中框架,更加轻巧、数据解析能力更强。先用fastify框架搭建一个web服务。


API

搭建之前先说下将要使用到的API。

fastify.register(plugin, [options])

在fastify框架中,它将一切资源都认为是一个插件,包括静态资源、路由、服务等。register将会创建一个新的作用域,如果你需要在register中使用decorate,这个变化将不会在register实例上展现。下文将讲述,如何处理这种情况。

fastify.decorate(attr,expression)

使用decorate可以对register实例的属性进行修改。


Server

//app.js
const fastify = require('fastify')();
fastify.addHook('onRequest', (req, res, next) => {
    console.log(req.url);
    next();
})
fastify.register(require('./route/our-db-connector'), {
    url: 'mongodb://***'
});
fastify.register(require('./route/our-first-route'),{ prefix: '/v1' });
fastify.listen(3000, function (err) {
    if (err) throw err
    fastify.log.info(`server listening on ${fastify.server.address().port}`)
})
  • fastify提供有hook机制,可以对request、response、send等进行监听。
  • register注册两个插件,数据库实例和路由实例
  • 监听3000端口

连接MongoDB数据库

//our-db-connector.js
const fp = require('fastify-plugin')
const MongoClient = require('mongodb').MongoClient;
async function db (fastify, options) {
  const url = options.url
  delete options.url
  const db = await MongoClient.connect(url, options)
  fastify.decorate('mongo', db)
}
module.exports = fp(db)

在这里需要注意的是decorate这个API的使用,因为register会创建新的作用域,但同时需要在fastify实例(即app.js)上绑定db对象。如果想要在register中使用decorate扩展基础服务中的fastify,你需要告诉fastify不再创建新的作用域,这里有两种解决方案。

方案一:使用fastify-plugin模块

const fp = require('fastify-plugin')

module.exports = fp(function (fastify, opts, next) {
  fastify.decorate('utility', () => {})
  next()
}, '0.x')

方案二:使用’skip-override’

function yourPlugin (fastify, opts, next) {
  fastify.decorate('utility', () => {})
  next()
}
yourPlugin[Symbol.for('skip-override')] = true
module.exports = yourPlugin

在这里推荐使用方案一,便于维护。本文使用的是方案一。


路由

//our-first-route.js
let opts = {
    name:{
        schema:{
            body:{
                type:'string',
            }
        }
    }
}

async function routes (fastify,options,next) {

    const collection = fastify.mongo.collection('user')

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

    fastify.get('/name/:name',opts.name,async (request,reply) =>{

        return {name:name}
    })
}

module.exports = routes
  • 调用app.js的fastify实例上的数据库,即fastify.mongo。
  • fastify支持async/await,这种情况下,只需要return,请求就会结束。
  • fastify支持schame,即我们看到的/name/:name后面的参数,用户可以预先定义请求的参数类型,以及返回的数据类型。若,数据类型不匹配时,会报错。这一机制,也是fastify在请求处理比express、restify都快的原因所在。

运行

node app.js
打开浏览器,在地址栏输入127.0.0.1:3000/v1。
为什么是v1?这是在app.js中有设置前置的原因,fastify.register(require(‘./route/our-first-route’),{ prefix: ‘/v1’ });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逛街的猫啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值