【问题标题】:Fastifyis not defined and fastify-postgres Fastify.pg.connect not workingFastify 没有定义并且 fastify-postgres Fastify.pg.connect 不工作
【发布时间】:2022-01-07 11:57:52
【问题描述】:

我已经这样定义了我的 fastify:

const fastify = require('fastify')({logger: true})

fastify
  .register(require('./setup/envs'))
  .after(async (err) => {
    if (err) console.log(err);

    fastify.register(require('./setup/db'))
    await fastify.after()
    
    fastify.register(require('./setup/jwt'))
    await fastify.after()

    fastify.register(require('./setup/auth'))
    await fastify.after()
    
    // load routes
    // fastify.register(require('./routes/test'))
    fastify.register(require('./routes/posts/index'), { prefix: '/posts' })
  })

const start = async () => {
  try {
    await fastify.ready()
    fastify.listen(3000)
  } catch (e) {
    fastify.log.error(e)
    process.exit(1)
  }
}

start();

现在在我的发布路线中,我有以下内容:

const postRoutes = require('../../controllers/posts');

async function PostRoutes(fastify, options) {
  fastify.addHook('preValidation', fastify.verifyJWT)
  fastify.addHook('preHandler', function (req, reply, done) {
    if (req.body) {
      req.log.info({ body: req.body }, 'parsed body')
    }
    if (req.params) {
      req.log.info({ params: req.body }, 'parsed params')
    }
    done()
  })

  // get all posts
  fastify.get('/:limit/:page', postRoutes.getPosts)

  fastify.post('/signup', async (req, reply) => {
    // some code
    const token = fastify.jwt.sign({ test: 'hello' })
    reply.send({ token })
  })

  fastify.get(
    "/test-auth",
    async function(request, reply) {
      return { test: 'auth' }
    }
  )
}

module.exports = PostRoutes;

我的控制器文件如下:

const fastify = require('fastify');

const getPosts = async (req, reply) => {
  try {
    const client = await fastify.pg.connect()
    const { rows } = await client.query(
      'SELECT * FROM POSTS LIMIT $1 OFFSET $2;', [req.params.limit, req.params.offset],
    )
    client.release()
    return rows
  } catch (e) {
    req.log.error('Getting posts failed with params')
    throw new Error(e)
  }
}

module.exports = {
  getPosts,

};

const client = await fastify.pg.connect() 给我的 fastify 没有定义,如果我需要在顶部添加 const fastify = require('fastify'),我会得到 TypeError: Cannot read properties of undefined (reading 'connect')

以下是我的 db.js:

const fastifyPlugin = require('fastify-plugin');
const fastifyPostgres = require('fastify-postgres');

async function dbConnector (fastify, options) {
  const dbUser = encodeURIComponent(fastify.config.DATABASE_USERNAME)
  const dbPassword = encodeURIComponent(fastify.config.DATABASE_PASSWORD);
  const dbHost = encodeURIComponent(process.env.DATABASE_HOST);
  const dbName = encodeURIComponent(fastify.config.DATABASE_NAME);

  fastify.register(fastifyPostgres, {
    connectionString: `postgres://${dbUser}:${dbPassword}@${dbHost}/${dbName}`
  })
}
// Wrapping a plugin function with fastify-plugin exposes the decorators
// and hooks, declared inside the plugin to the parent scope.
module.exports = fastifyPlugin(dbConnector);

【问题讨论】:

    标签: node.js postgresql fastify


    【解决方案1】:

    我不得不将路线更改为: fastify.get('/:limit/:page', (req, reply) => postRoutes.getPosts(fastify, req, reply))

    然后我就可以访问控制器中的 fastify 对象了,哈哈

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 2022-12-05
      • 2021-12-07
      • 2021-10-08
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多