Next.js中如何用node-postgres实现<Revenue>类型解析?
用node-postgres实现类型解析的解决方案
核心思路
node-postgres的pool.query()本身支持TypeScript泛型参数,可直接传入Revenue类型约束返回结果,和@vercel/postgres的sql<Revenue>逻辑一致,仅需处理返回数据的结构差异。
修改后的代码示例
假设你的Revenue类型定义如下(对应definitions.ts中的内容):
export type Revenue = { id: string; month: string; revenue: number; };
直接给pool.query()添加泛型参数,并从返回结果中提取rows(node-postgres会把查询数据放在rows数组内):
import { Pool } from 'pg'; import type { Revenue } from './definitions'; // 导入你的类型定义 // 初始化连接池(替换为你的本地PostgreSQL配置) const pool = new Pool({ user: '你的数据库用户名', host: 'localhost', database: '你的数据库名', password: '你的数据库密码', port: 5432, }); async function getRevenue() { // 传入Revenue泛型约束查询结果类型 const queryResult = await pool.query<Revenue>(`SELECT * FROM revenue`); // queryResult.rows即为符合Revenue[]类型的数据数组 const data = queryResult.rows; return data; }
关键说明
pool.query<Revenue>会让TypeScript识别到每一行返回数据都匹配Revenue类型结构- node-postgres的查询结果对象包含
rows(实际数据)、rowCount等属性,这和@vercel/postgres的sql函数直接返回数据的方式不同,需注意提取rows - 确保
Revenue类型的字段和数据库revenue表的字段完全对应,避免类型不兼容问题
内容的提问来源于stack exchange,提问作者Theo
相关产品推荐
相关产品推荐

