【问题标题】:Pass fastify instance to controllers at a top level将 fastify 实例传递给顶层控制器
【发布时间】:2021-11-09 22:49:58
【问题描述】:

与其将fastify instance 传递给每个函数,我怎样才能只在顶层传递一次,以便控制器中的所有函数都可以使用它?

// route file
import { FastifyPluginAsync } from 'fastify'

import RootController from '../root.controller'

const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
  fastify.get('/', RootController.index(fastify))
  fastify.get('/show', RootController.show(fastify))
}

export default root
// controller file
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'

export default {
  index: (fastify: FastifyInstance) => async (request: FastifyRequest, reply: FastifyReply) => {
    const hugs = fastify.someSupport()

    reply.send({ status: 'ok', love: hugs })
  },

  show: (fastify: FastifyInstance) => async (request: FastifyRequest, reply: FastifyReply) => {
    const hugs = 'extra ' + fastify.someSupport()

    reply.send({ status: 'ok', love: hugs })
  }
}

【问题讨论】:

    标签: javascript node.js fastify


    【解决方案1】:

    答案是使用闭包进行简单的机械重构:

    // controller file
    import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'
    
    export default async function installRootController(fastify: FastifyInstance, opts): Promise<void> {
      fastify.get('/', async (request: FastifyRequest, reply: FastifyReply) => {
        const hugs = fastify.someSupport()
    
        reply.send({ status: 'ok', love: hugs })
      });
    
      fastify.get('/show', async (request: FastifyRequest, reply: FastifyReply) => {
        const hugs = 'extra ' + fastify.someSupport()
    
        reply.send({ status: 'ok', love: hugs })
      });
    };
    

    内部函数(//show 的异步处理程序)可以访问 fastify,因为它可以从周围函数的词法范围访问。这使您可以将整个“控制器”封装为 Fastify 插件,并可以像这样安装:

    
    fastify.register(installRootController);
    

    请注意,“路由”文件现在没有用了。

    【讨论】:

    • 谢谢 Rob,这当然是我没有考虑过的一种方法。我目前正在使用github.com/fastify/fastify-autoload 加载该文件夹中的所有路由,因为它提供了一些额外的好处。如果我仍然想使用autoload plugin,除了您的答案之外还有其他方法可以实现吗?
    • 不确定,但我认为 fastify-autoload 的文档暗示您可以导出一个完整的插件,它应该将 fastify 实例作为参数 - 请参阅options 之后的自述文件中的 sn-p部分。看起来和我的重构函数导出一模一样!
    • 是的,和你写的一样……我想我想做的是将逻辑从路由闭包移到控制器中,以保持路由干净。
    • 你总是可以将控制器变成一个类,并使用依赖注入传递 fastify 实例。不过我也不会太担心——毕竟这里的 Controller 是“纯属虚构”,并不代表现实生活中的概念。它仅作为路线分组设施存在,闭包也可以发挥作用。
    • 同意 Rob... 我确实曾经使用过一个类,但看起来并不优雅。来自强大的 PHP(laravel)背景,我想现在我需要换个思路。感谢您的时间和精力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    相关资源
    最近更新 更多