首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未定义的Fastify CLI装饰器

问未定义的Fastify CLI装饰器
EN

Stack Overflow用户
提问于 2022-10-13 14:52:12
回答 1查看 76关注 0票数 0

我正在使用筋膜-cli构建我的服务器应用程序。

对于测试,我想生成一些测试JWT。因此,我想使用sign方法的fastify-jwt插件。

如果我使用fastify start -l info ./src/app.js运行应用程序,一切都可以按预期工作,并且可以访问装饰器。

但是在测试设置中,我得到了一个错误,即jwt装饰器是未定义的。似乎装潢工没有暴露出来,我只是找不到任何错误。对于测试,我在以下命令中使用节点抽头:tap \"test/**/*.test.js\" --reporter=list

app.js

代码语言:javascript
复制
import { dirname, join } from 'path'
import autoload from '@fastify/autoload'
import { fileURLToPath } from 'url'
import jwt from '@fastify/jwt'

export const options = {
  ignoreTrailingSlash: true,
  logger: true
}

export default async (fastify, opts) => {
  await fastify.register(jwt, {
    secret: process.env.JWT_SECRET
  })

  // autoload plugins and routes
  await fastify.register(autoload, {
    dir: join(dirname(fileURLToPath(import.meta.url)), 'plugins'),
    options: Object.assign({}, opts),
    forceESM: true,
  })

  await fastify.register(autoload, {
    dir: join(dirname(fileURLToPath(import.meta.url)), 'routes'),
    options: Object.assign({}, opts),
    forceESM: true
  })
}

helper.js

代码语言:javascript
复制
import { fileURLToPath } from 'url'
import helper from 'fastify-cli/helper.js'
import path from 'path'

// config for testing
export const config = () => {
  return {}
}

export const build = async (t) => {
  const argv = [
    path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'app.js')
  ]

  const app = await helper.build(argv, config())

  t.teardown(app.close.bind(app))

  return app
}

root.test.js

代码语言:javascript
复制
import { auth, build } from '../helper.js'
import { test } from 'tap'

test('requests the "/" route', async t => {
  t.plan(1)

  const app = await build(t)

  const token = app.jwt.sign({ ... }) //-> jwt is undefined

  const res = await app.inject({
    method: 'GET',
    url: '/'
  })

  t.equal(res.statusCode, 200, 'returns a status code of 200')
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-13 18:17:10

问题是您的应用程序关系图如下所示:

​

​

当您编写const app = await build(t)时,app变量指向Root Context,但是Your app.js包含jwt装饰符。

要解决这个问题,只需将app.js文件与fastify-plugin包装在一起,因为它破坏了封装:

代码语言:javascript
复制
import fp from 'fastify-plugin'

export default fp(async (fastify, opts) => { ... })

注意:您可以通过使用fastify-overview (和fastify-overview-ui插件一起)来可视化这个结构:

​

​

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74057840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档