推荐答案
在 Fastify 中与 PostgreSQL 集成,通常使用 fastify-postgres 插件。以下是一个简单的示例代码:
// www.javascriptcn.com code example
const fastify = require('fastify')({ logger: true });
const fastifyPostgres = require('fastify-postgres');
// 注册 fastify-postgres 插件
fastify.register(fastifyPostgres, {
connectionString: 'postgres://user:password@localhost/database'
});
// 定义一个路由来查询数据库
fastify.get('/users', async (request, reply) => {
const client = await fastify.pg.connect();
try {
const { rows } = await client.query('SELECT * FROM users');
return rows;
} finally {
client.release();
}
});
// 启动服务器
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info('Server listening on http://localhost:3000');
});本题详细解读
1. 安装依赖
首先,你需要安装 fastify-postgres 插件和 pg(PostgreSQL 客户端库):
npm install fastify-postgres pg
2. 注册插件
在 Fastify 应用中,使用 fastify.register 方法注册 fastify-postgres 插件。你需要提供一个连接字符串,格式为 postgres://user:password@localhost/database。
fastify.register(fastifyPostgres, {
connectionString: 'postgres://user:password@localhost/database'
});3. 使用数据库连接
在路由处理函数中,你可以通过 fastify.pg.connect() 获取一个数据库连接。使用 client.query 执行 SQL 查询,并在完成后调用 client.release() 释放连接。
// www.javascriptcn.com code example
fastify.get('/users', async (request, reply) => {
const client = await fastify.pg.connect();
try {
const { rows } = await client.query('SELECT * FROM users');
return rows;
} finally {
client.release();
}
});4. 启动服务器
最后,启动 Fastify 服务器并监听指定端口。
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info('Server listening on http://localhost:3000');
});通过以上步骤,你就可以在 Fastify 应用中成功集成 PostgreSQL 数据库。