NodeJS Fastify -访问控制器内包含在父函数中的函数?

cvxl0en2  于 2023-03-12  发布在  Node.js
关注(0)|答案(1)|浏览(114)

如何访问包含在父函数中的控制器中的函数?在下面的示例中,我无法访问getConfig()函数。
我以这种方式设置它的原因是,我仍然可以访问控制器中的Fastify示例。

路由.js

import formbody from '@fastify/formbody'
import controller from '../../controllers/controller.js'

const routes = (fastify, options, done) => {

   fastify.register(formbody)
   fastify.register(controller)

   fastify.get('/get-config', (req, rep) => {
        getConfig(req, rep)
    })
}

export default routes

控制器.js

import merchant from '../models/merchant.js'

const controller = (fastify, options, done) => {

   const srvcMerchant = new merchant(fastify)

   const getConfig = async (req, rep) => {
        const config = await srvcMerchant.getConfig(req.id);

        if (!config) {
            return rep
                .status(404)
                .send({ message: 'Not found' })
        }

        rep.send(config);
    }
}

export default controller
t1rydlwq

t1rydlwq1#

您需要编写一个插件(没有封装)并添加一个装饰器:

控制器.js

import merchant from '../models/merchant.js'
import fp from 'fastify-plugin'

const controller = (fastify, options, done) => {

   const srvcMerchant = new merchant(fastify)

   const getConfig = async (req, rep) => {
        const config = await srvcMerchant.getConfig(req.id);

        if (!config) {
            rep.code(404)
            return { message: 'Not found' }
        }

        return config;
    }

    fastify.decorate('foo', getConfig)
    done()
}

export default fp(controller)

然后在您的路线中:

fastify.get('/get-config', async (req, rep) => {
    return fastify.foo(req, rep)
})

其他有用的读物:

相关问题