当前位置: 首页 > news >正文

hono+postgresql+CURD

  • 数据库: PostgreSQL
  • 用户名: postgres
  • 密码: 123

第一步:环境准备

在开始之前,请确保你的电脑上已经安装了以下软件:

  • Node.js: 版本 18 或更高。
  • PostgreSQL: 确保 PostgreSQL 服务已经安装并正在运行。

你可以使用 node -v 和 psql --version 来检查它们是否已正确安装。


第二步:数据库和数据表设置

我们需要先创建一个数据库和一个用于存放用户数据的表。

登录 PostgreSQL:
打开你的终端或命令行工具,使用 psql 命令登录到 PostgreSQL。你可能需要根据你的安装方式指定用户。

  • Generated bash
psql -U postgres

Use code with caution.Bash

创建数据库:
我们将创建一个名为 hono_db 的数据库。

  • Generated sql
CREATE DATABASE hono_db;

Use code with caution.SQL

连接到新数据库:
使用 \c 命令连接到刚刚创建的数据库。

  • Generated sql
\c hono_db

Use code with caution.SQL

创建用户表 (users):
我们将创建一个 users 表,包含 id, name, 和 email 字段。

  • Generated sql
CREATE TABLE users (id SERIAL PRIMARY KEY,name VARCHAR(100) NOT NULL,email VARCHAR(100) UNIQUE NOT NULL,created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

Use code with caution.SQL

    • SERIAL PRIMARY KEY: 自动递增的整数作为主键。
    • VARCHAR(100): 存储姓名和邮箱。
    • NOT NULL 和 UNIQUE: 确保数据的完整性。
    • created_at: 记录创建时间。

现在数据库已经准备好了。


第三步:项目初始化与依赖安装

创建项目文件夹:

  • Generated bash
mkdir hono-postgres-crud
cd hono-postgres-crud

Use code with caution.Bash

初始化 Node.js 项目:

  • Generated bash
npm init -y

Use code with caution.Bash

安装 Hono 和相关依赖:

    • hono: Hono 核心库。
    • @hono/node-server: 在 Node.js 环境中运行 Hono 的适配器。
    • pg: Node.js 的 PostgreSQL 客户端库,用于连接和查询数据库。
    • dotenv: 用于管理环境变量(如数据库密码),这是最佳实践。
  • Generated bash
npm install hono @hono/node-server pg dotenv

Use code with caution.Bash

安装开发依赖 (TypeScript):
我们将使用 TypeScript 来编写代码,这能提供更好的类型安全和开发体验。

    • typescript: TypeScript 编译器。
    • tsx: 一个非常快速的 TypeScript 执行器,用于开发。
    • @types/...: 对应库的类型定义文件。
  • Generated bash
npm install -D typescript @types/node @types/pg tsx

Use code with caution.Bash


第四步:项目配置

配置 TypeScript (tsconfig.json):
在项目根目录创建 tsconfig.json 文件,并添加以下内容:

  • Generated json
{"compilerOptions": {"target": "ESNext","module": "ESNext","moduleResolution": "node","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"outDir": "./dist"}
}

Use code with caution.Json

配置环境变量 (.env 文件):
在项目根目录创建 .env 文件。不要将此文件提交到 Git 仓库。我们在这里存放数据库连接信息。

  • Generated code
# PostgreSQL Connection String
# 格式: postgresql://[user]:[password]@[host]:[port]/[database]
DATABASE_URL="postgresql://postgres:123@localhost:5432/hono_db"

Use code with caution.

注意:

    • 请将 postgresql:123 替换成你自己的用户名和密码。
    • localhost:5432 是 PostgreSQL 的默认主机和端口。
    • hono_db 是我们在第二步中创建的数据库名。

添加 package.json 脚本:
打开 package.json 文件,在 "scripts" 部分添加一个 dev 命令,以便用 tsx 启动开发服务器。

  • Generated json
"scripts": {"dev": "tsx --watch src/index.ts"
},

Use code with caution.Json


第五步:编写 Hono 应用代码

创建 src 目录和 index.ts 文件:

  • Generated bash
mkdir src
touch src/index.ts

Use code with caution.Bash

编写 src/index.ts 文件:
这是我们项目的核心文件。我们将在这里设置 Hono 应用、连接数据库并定义所有 CRUD 路由。

  • Generated typescript
import { Hono } from 'hono';
import { logger } from 'hono/logger';
import { serve } from '@hono/node-server';
import { Pool } from 'pg';
import 'dotenv/config'; // 自动加载 .env 文件// 1. 初始化 Hono 应用
const app = new Hono();// 2. 初始化 PostgreSQL 连接池
const pool = new Pool({connectionString: process.env.DATABASE_URL,
});// 检查数据库连接
pool.connect((err, client, release) => {if (err) {return console.error('Error acquiring client', err.stack);}console.log('Successfully connected to PostgreSQL!');client.release();
});// 3. 中间件
app.use('*', logger());// 定义 User 类型 (用于 TypeScript)
type User = {id: number;name: string;email: string;
};// 4. 定义 CRUD 路由// CREATE: 创建一个新用户
app.post('/users', async (c) => {try {const { name, email } = await c.req.json<{ name: string; email: string }>();if (!name || !email) {return c.json({ error: 'Name and email are required' }, 400);}const result = await pool.query('INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',[name, email]);const newUser: User = result.rows[0];return c.json(newUser, 201); // 201 Created} catch (error) {console.error('Create user error:', error);return c.json({ error: 'Failed to create user' }, 500);}
});// READ: 获取所有用户
app.get('/users', async (c) => {try {const result = await pool.query('SELECT * FROM users ORDER BY id ASC');const users: User[] = result.rows;return c.json(users);} catch (error) {console.error('Get all users error:', error);return c.json({ error: 'Failed to fetch users' }, 500);}
});// READ: 获取单个用户
app.get('/users/:id', async (c) => {try {const id = parseInt(c.req.param('id'));const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);if (result.rows.length === 0) {return c.json({ error: 'User not found' }, 404);}const user: User = result.rows[0];return c.json(user);} catch (error) {console.error('Get single user error:', error);return c.json({ error: 'Failed to fetch user' }, 500);}
});// UPDATE: 更新一个用户
app.put('/users/:id', async (c) => {try {const id = parseInt(c.req.param('id'));const { name, email } = await c.req.json<{ name: string; email: string }>();if (!name || !email) {return c.json({ error: 'Name and email are required' }, 400);}const result = await pool.query('UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING *',[name, email, id]);if (result.rows.length === 0) {return c.json({ error: 'User not found' }, 404);}const updatedUser: User = result.rows[0];return c.json(updatedUser);} catch (error) {console.error('Update user error:', error);return c.json({ error: 'Failed to update user' }, 500);}
});// DELETE: 删除一个用户
app.delete('/users/:id', async (c) => {try {const id = parseInt(c.req.param('id'));const result = await pool.query('DELETE FROM users WHERE id = $1 RETURNING *', [id]);if (result.rowCount === 0) {return c.json({ error: 'User not found' }, 404);}return c.json({ message: `User with id ${id} deleted successfully` });} catch (error) {console.error('Delete user error:', error);return c.json({ error: 'Failed to delete user' }, 500);}
});// 5. 启动服务器
const port = 3000;
console.log(`Server is running on port ${port}`);serve({fetch: app.fetch,port,
});

Use code with caution.TypeScript


第六步:运行和测试应用

启动开发服务器:
在你的终端中,运行以下命令:

  • Generated bash
npm run dev

Use code with caution.Bash

如果一切顺利,你会看到如下输出:

Generated code

Successfully connected to PostgreSQL!
Server is running on port 3000

Use code with caution.

  • 使用 curl 或 Postman 测试 API:
    打开另一个终端,使用 curl 命令来测试你的 CRUD 端点。

CREATE (创建用户)

    • Generated bash
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com"}'

Use code with caution.Bash

你应该会收到类似 {"id":1,"name":"Alice","email":"alice@example.com"} 的响应。

再创建一个用户:

Generated bash

curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name": "Bob", "email": "bob@example.com"}'

Use code with caution.Bash

READ (获取所有用户)

    • Generated bash
curl http://localhost:3000/users

Use code with caution.Bash

你应该会看到一个包含 Alice 和 Bob 的 JSON 数组。

READ (获取单个用户)
假设 Alice 的 ID 是 1。

    • Generated bash
curl http://localhost:3000/users/1

Use code with caution.Bash

你应该会只看到 Alice 的信息。

UPDATE (更新用户)
更新 ID 为 1 的用户的信息。

    • Generated bash
curl -X PUT http://localhost:3000/users/1 \
-H "Content-Type: application/json" \
-d '{"name": "Alice Smith", "email": "alice.smith@example.com"}'

Use code with caution.Bash

你应该会收到更新后的用户信息。

DELETE (删除用户)
删除 ID 为 2 的用户 (Bob)。

    • Generated bash
curl -X DELETE http://localhost:3000/users/2

Use code with caution.Bash

你应该会收到 {"message":"User with id 2 deleted successfully"}。

再次检查
再次获取所有用户,确认 Bob 已经被删除。

    • Generated bash
curl http://localhost:3000/users

Use code with caution.Bash


第七步:总结与后续步骤

恭喜!你已经成功创建了一个使用 Hono.js 和 PostgreSQL 的全功能 CRUD API。

后续可以优化的方向:

  • 输入验证: 使用 @hono/zod-validator 和 Zod 库来验证请求体,确保传入的数据格式正确。
  • 错误处理: 创建一个全局的错误处理中间件来统一处理和格式化错误响应。
  • 代码结构: 当项目变大时,可以将路由、数据库逻辑(也称为 Repository 或 Service 层)分离到不同的文件中,使代码更易于维护。
  • 使用 ORM: 对于更复杂的项目,可以考虑使用像 Drizzle ORM 或 Prisma 这样的 ORM,它们可以简化数据库操作并提供更强的类型安全。

CRUD.http

// 创建用户
POST http://localhost:8080/users
Content-Type: application/json{"name": "Bob1","email": "bob1@example.com"
}###
// 获取所有用户
GET http://localhost:8080/users###
// 获取单个用户
GET http://localhost:8080/users/5###
// 更新用户
PUT http://localhost:8080/users/5
Content-Type: application/json{"name": "Bob2","email": "bob2@example.com"
}###
// 删除用户
DELETE http://localhost:8080/users/1

http://www.lqws.cn/news/589303.html

相关文章:

  • YOLOv13:最新的YOLO目标检测算法
  • Windows11系统中安装docker并配置docker镜像到pycharm中
  • 文旅数字孪生交付生态链:集成-交付-运维“三位一体”,100+案例助力行业数字化转型
  • 腾讯云空间,高性能显卡云,安装xinference报错,pip install 空间不够用了
  • WOLA(Weighted Overlap-Add)方法详解
  • 实战避坑:MyBatis中${}拼接如何优雅又安全?
  • Python 数据分析与机器学习入门 (二):NumPy 核心教程,玩转多维数组
  • Redis 集群
  • SQLite 安装使用教程
  • 长短期记忆网络(LSTM):让神经网络拥有 “持久记忆力” 的神奇魔法
  • 反射,枚举和lambda表达式
  • Bessel位势方程求解步骤
  • 国产化替换中政务行业通用的解决方案是什么?需要注意的事项有哪些?
  • 链表题解——移除链表元素【LeetCode】
  • 基于DSP的边缘检测与图像锐化算法研究与实现
  • ACE之ACE_NonBlocking_Connect_Handler问题分析
  • Vue防抖节流
  • localStorage 和 sessionStorage
  • ViT与CLIP:图像×文本 多模态读心术揭秘
  • python开篇介绍
  • 人工智能参与高考作文写作的实证研究
  • 大根堆加小根堆查找中位数o(N)时间复杂度
  • I/O I/O基本概念与基本I/O函数 6.30
  • CppCon 2018 学习:An allocator is a handle to a heap Lessons learned from std::pmr
  • 第八章IPv4、IPv6、ICMP、ARP、RARP
  • Mysql索引优化
  • 矩阵方程 线性代数
  • 深度学习04 卷积神经网络CNN
  • docker使用容器网络
  • SQL学习笔记5