1.4 我想使用Postgresql的Docker映像,在本机上面建立一个上面实例所用的数据库系统,相关的详细步骤与代码
要在本机上使用 PostgreSQL 的 Docker 映像来建立一个用于上述实例的数据库系统,以下是详细步骤和代码示例。
1. 安装 Docker¶
如果尚未安装 Docker,请访问 Docker 官方网站 下载并安装 Docker。
2. 拉取并运行 PostgreSQL Docker 映像¶
使用以下命令来拉取并运行 PostgreSQL 容器:
这个命令会执行以下操作:
- 使用 postgres 映像。
- 创建一个名为 my-postgres 的容器。
- 设置 PostgreSQL 的密码为 mysecretpassword。
- 将容器的 5432 端口映射到本机的 5432 端口。
3. 安装 Prisma 和初始化项目¶
如果还没有创建项目,请按照以下步骤操作:
初始化 Prisma:
4. 配置 prisma/schema.prisma¶
编辑 prisma/schema.prisma 文件来配置 PostgreSQL 作为数据库,并定义 User 和 Post 模型:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String
author User @relation(fields: [authorId], references: [id])
authorId Int
}
5. 配置环境变量¶
在项目根目录下创建一个 .env 文件,并添加以下内容来配置数据库连接字符串:
6. 迁移数据库¶
使用 Bun 运行 Prisma 迁移命令来生成数据库并创建表:
7. 生成 Prisma 客户端¶
生成 Prisma 客户端:
8. 更新项目结构和代码¶
确保项目结构如下:
elysia-app/
├── prisma/
│ └── schema.prisma
├── src/
│ ├── index.ts
│ ├── routes/
│ │ ├── users.ts
│ │ ├── posts.ts
│ └── models/
│ ├── user.ts
│ └── post.ts
├── package.json
└── tsconfig.json
更新用户路由 src/routes/users.ts¶
import { Router } from "elysia";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const userRouter = new Router()
.get("/", async (req, res) => {
const users = await prisma.user.findMany({
include: { posts: true },
});
res.json(users);
})
.get("/:id", async (req, res) => {
const user = await prisma.user.findUnique({
where: { id: parseInt(req.params.id) },
include: { posts: true },
});
if (user) {
res.json(user);
} else {
res.status(404).send("User not found");
}
})
.post("/", async (req, res) => {
const newUser = await prisma.user.create({
data: req.body,
});
res.status(201).json(newUser);
});
更新帖子路由 src/routes/posts.ts¶
import { Router } from "elysia";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export const postRouter = new Router()
.get("/", async (req, res) => {
const posts = await prisma.post.findMany({
include: { author: true },
});
res.json(posts);
})
.get("/:id", async (req, res) => {
const post = await prisma.post.findUnique({
where: { id: parseInt(req.params.id) },
include: { author: true },
});
if (post) {
res.json(post);
} else {
res.status(404).send("Post not found");
}
})
.post("/", async (req, res) => {
const newPost = await prisma.post.create({
data: req.body,
});
res.status(201).json(newPost);
});
主文件 src/index.ts¶
import { Elysia } from "elysia";
import { userRouter } from "./routes/users";
import { postRouter } from "./routes/posts";
const app = new Elysia()
.use("/users", userRouter)
.use("/posts", postRouter);
app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});
运行项目¶
使用以下命令运行项目:
总结¶
通过使用 PostgreSQL 的 Docker 映像,你可以轻松地在本地设置和运行数据库。在此示例中,我们展示了如何使用 Docker 运行 PostgreSQL 并配置 Prisma 与之交互。这样,你可以利用 PostgreSQL 的强大功能和 Prisma 的便捷性,构建高效的后端应用。