Skip to main content

集成使用 Deno Deploy 部署 Prisma Postgres

15 min

Deno 部署 包含一项功能,允许你直接在平台内配置 Prisma Postgres 数据库。本指南演示了如何使用一个最小化的 Deno 应用(该应用会记录对数据库的 HTTP 请求)将 Prisma Postgres 集成到 Deno Deploy 项目中。

¥Deno Deploy includes a feature that allows you to provision a Prisma Postgres database directly within the platform. This guide demonstrates how to integrate Prisma Postgres in a Deno Deploy project using a minimal Deno application that logs HTTP requests to the database.

在本指南结束时,你将拥有一个已部署的 Deno 应用,该应用可以使用 Prisma Client 和 runtime = "deno" 对在 Deno Deploy 中配置的 Prisma Postgres 数据库进行读写操作。

¥By the end of this guide, you will have a deployed Deno app that writes to and reads from a Prisma Postgres database provisioned in Deno Deploy, using Prisma Client with runtime = "deno".

先决条件

¥Prerequisites

1. 创建并设置一个新的 Deno 项目

¥ Create and set up a new Deno project

使用 deno init 命令创建一个新的 Deno 项目,该命令会生成一个包含主入口文件和配置的基本项目结构。

¥Create a new Deno project using the deno init command, which generates a basic project structure with a main entry file and configuration.

deno init prisma-postgres-deno-deploy
cd prisma-postgres-deno-deploy

1.1 配置 VS Code 以支持 Deno

¥1.1 Configure VS Code for Deno

为确保 VS Code 将其识别为 Deno 项目并提供正确的 TypeScript 验证,你需要初始化工作区。如果没有此功能,VS Code 在使用 Deno 特有的 API(例如 Deno.serve)时会显示错误。

¥To ensure VS Code recognizes this as a Deno project and provides proper TypeScript validation, you need to initialize the workspace. Without this, VS Code will show errors when using Deno-specific APIs like Deno.serve.

安装 VS Code 的 Deno 扩展,然后:

¥Install the Deno extension for VS Code, then:

  1. 选择“视图”>“命令面板”(或在 macOS 上按 Cmd+Shift+P,或在 Windows 上按 Ctrl+Shift+P)。

    ¥Select View > Command Palette (or press Cmd+Shift+P on macOS or Ctrl+Shift+P on Windows)

  2. 运行 Deno 命令:初始化工作区配置

    ¥Run the command Deno: Initialize Workspace Configuration

1.2 创建基本 HTTP 服务器

¥1.2 Create a basic HTTP server

更新 main.ts 文件以创建一个简单的 HTTP 服务器,该服务器使用 "Hello, World!" 进行响应,从而在添加数据库功能之前为你的应用奠定基础。

¥Update the main.ts file to create a simple HTTP server that responds with "Hello, World!", establishing the foundation for your application before adding database functionality.

main.ts
function handler(_req: Request): Response {
return new Response("Hello, World!");
}

Deno.serve(handler);

你可以通过运行以下命令在本地测试服务器:

¥You can test the server locally by running:

deno run dev

在浏览器中访问 localhost:8000,查看应用的运行情况。

¥Visit localhost:8000 in your browser to see the application running.

1.3 将初始项目推送到 GitHub

¥1.3 Push initial project to GitHub

要将你的项目连接到 Deno Deploy 并获取数据库连接字符串,你需要成功部署。设置 GitHub 仓库并将你的项目推送到该仓库。

¥To connect your project to Deno Deploy and get a database connection string, you need to have a successful deployment. Set up a GitHub repository and push your project to it.

2. 将项目部署到 Deno Deploy

¥ Deploy the project to Deno Deploy

将你的存储库部署到 Deno Deploy任何后续提交都会触发自动重新部署。你需要立即部署,因为数据库字符串需要成功部署才能生成。

¥Deploy your repository to Deno Deploy. Any subsequent commits will trigger automatic redeployments. You need to deploy now, as the database string requires a successful deployment to generate.

  1. 访问 Deno Deploy 控制面板 并选择“新建应用”。

    ¥Navigate to the Deno Deploy dashboard and select New App

  2. 按照 GitHub 的提示配置 GitHub 应用权限。

    ¥Configure GitHub app permissions by following GitHub's prompts

  3. 在 Deno Deploy 界面中选择你的 GitHub 仓库

    ¥Choose your GitHub repository in the Deno Deploy interface

  4. 点击“创建应用”完成部署。

    ¥Click Create App to complete the deployment

应用将自动部署。

¥The application will deploy automatically.

3. 配置 Prisma Postgres 数据库

¥ Provision a Prisma Postgres database

在 Deno Deploy 中配置 Prisma Postgres 数据库,并将其链接到你的应用:

¥Provision a Prisma Postgres database in Deno Deploy, and link it to your application:

  1. 转到 Deno Deploy 控制面板中的“数据库”部分

    ¥Go to the Databases section in the Deno Deploy dashboard

  2. 选择“配置数据库”,然后选择 Prisma Postgres。

    ¥Select Provision Database and choose Prisma Postgres

  3. 完成数据库配置并确认配置。

    ¥Complete the database configuration and confirm provisioning

  4. 点击“分配”,然后选择你的应用。

    ¥Click Assign and select your application

  5. 复制生产环境连接字符串

    ¥Copy the Production connection string

  6. 将连接字符串添加到你的 .env 文件中:

    ¥Add the connection string to your .env file:

DATABASE_URL="postgresql://<username>:<password>@db.prisma.io:5432/<database_name>-production"

4. 配置 Prisma ORM

¥ Configure Prisma ORM

4.1 启用环境变量

¥4.1 Enable environment variables

要在本地开发期间访问数据库连接字符串,请配置 Deno 以使用 --env-file 标志从 .env 文件加载环境变量。

¥To access the database connection string during local development, configure Deno to load environment variables from your .env file using the --env-file flag.

更新 devdeno.json 中的任务:

¥Update the dev task in deno.json:

deno.json
{
"tasks": {
"dev": "deno run --watch --env-file main.ts"
}
}

4.2 初始化 Prisma 并创建架构

¥4.2 Initialize Prisma and create schema

安装 Prisma 客户端、PostgreSQL 适配器和开发依赖:

¥Install the Prisma Client, PostgreSQL adapter, and development dependencies:

deno install npm:@prisma/client npm:@prisma/adapter-pg npm:pg npm:prisma npm:@types/pg

在你的项目中初始化 Prisma,这将创建定义数据库模型所需的配置文件和文件夹结构。

¥Initialize Prisma in your project, which creates the necessary configuration files and folder structure for defining your database models.

npx prisma init

使用以下更改更新 Prisma 模式:

¥Update the Prisma schema with these changes:

  1. 将客户端输出从 prisma-client-js 更改为 prisma-client

    ¥Change the client output from prisma-client-js to prisma-client.

  2. 添加 Deno 运行时配置。(这是 Deno 正常运行所必需的)

    ¥Add the Deno runtime configuration. (This is required for Deno to run properly)

  3. 添加用于存储请求信息的日志模型。

    ¥Add the Log model for storing request information.

prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
runtime = "deno"
}

datasource db {
provider = "postgresql"
}

model Log {
id Int @id @default(autoincrement())
level Level
message String
meta Json
}

enum Level {
Info
Warn
Error
}

4.3 生成并应用迁移

¥4.3 Generate and apply migrations

迁移会根据你的 Prisma 模式创建实际的数据库表。此命令生成 SQL 迁移文件并针对你的数据库执行这些文件,从而创建具有指定字段的 Log 表。

¥Migrations create the actual database tables based on your Prisma schema. This command generates SQL migration files and executes them against your database, creating the Log table with the specified fields.

deno run -A npm:prisma migrate dev --name init
deno run -A npm:prisma generate

5. 更新应用以使用 Prisma

¥ Update the application to use Prisma

数据库配置完成后,更新你的应用以与之交互。此实现创建了一个日志系统,该系统捕获每个 HTTP 请求,将其存储在数据库中,并将日志条目以 JSON 格式返回。

¥Now that the database is configured, update your application to interact with it. This implementation creates a logging system that captures every HTTP request, stores it in the database, and returns the logged entry as JSON.

main.ts
import { PrismaClient } from "./generated/prisma/client.ts";
import { PrismaPg } from "npm:@prisma/adapter-pg";
import process from "node:process";

const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
});

const prisma = new PrismaClient({
adapter,
});

async function handler(request: Request) {
const url = new URL(request.url);
if (url.pathname === "/favicon.ico") {
return new Response(null, { status: 204 });
}

const log = await prisma.log.create({
data: {
level: "Info",
message: `${request.method} ${request.url}`,
meta: {
headers: JSON.stringify(request.headers),
},
},
});
const body = JSON.stringify(log, null, 2);
return new Response(body, {
headers: { "content-type": "application/json; charset=utf-8" },
});
}

Deno.serve(handler);

在本地运行以下命令测试应用:

¥Test the application locally by running:

deno run dev
注意

它可能会请求访问你的环境变量。选择“允许”以授予访问权限。

¥It may ask you for access to your environment variables. Select Allow to grant access.

在浏览器中访问 localhost:8000,查看应用的运行情况。你应该看到一个包含日志条目的 JSON 响应:

¥Visit localhost:8000 in your browser to see the application running. You should see a JSON response containing the log entry:

{
"id": 1,
"level": "Info",
"message": "GET http://localhost:8000/",
"meta": {
"headers": "..."
}
}

6. 部署应用

¥ Deploy the application

构建命令必须生成 Prisma Client 代码,以确保其在生产环境中可用。

¥The build command must generate the Prisma Client code to ensure it is available in production.

6.1 更新 Deno Deploy 中的构建命令

¥6.1 Update build command in Deno Deploy

  1. 在 Deno Deploy 中找到应用,然后单击“设置”

    ¥Go to the application in Deno Deploy and click Settings

  2. 在“构建配置”下,点击“编辑”并将 deno run -A npm:prisma generate 添加到构建命令中。

    ¥Under Build configuration, hit Edit and add deno run -A npm:prisma generate to the build command

  3. 点击“保存”

    ¥Click Save

6.2 将更改推送到 GitHub

¥6.2 Push changes to GitHub

提交并推送更改以触发自动部署。

¥Commit and push your changes to trigger an automatic deployment:

git add .
git commit -m "added prisma"
git push

返回 Deno Deploy,你应该会看到构建成功的提示。部署完成后,单击仪表板右上角的部署 URL。

¥Navigate back to Deno Deploy and you should see a successful build. Once deployed, click the deployment URL at the top right of the dashboard.

6.3 验证部署

¥6.3 Verify the deployment

访问已部署的应用时,你应该会看到类似如下的响应:

¥When you visit your deployed application, you should see a response that looks like this:

{
"id": 1,
"level": "Info",
"message": "GET https://prisma-postgres-deno-deploy.<org-name>.deno.net/",
"meta": {
"headers": "{}"
}
}

你已完成!每次刷新页面时,都会在数据库中创建一个新的日志条目。

¥You're done! Each time you refresh the page, a new log entry is created in your database.

后续步骤

¥Next Steps

现在你已经拥有一个运行正常的 Deno 应用并连接到 Prisma Postgres 数据库,你可以:

¥Now that you have a working Deno app connected to a Prisma Postgres database, you can:

  • 增强你的数据模型 - 向 Prisma schema 添加关系、验证和索引。

    ¥Enhance your data model - Add relationships, validations, and indexes to your Prisma schema

  • 保护你的 API - 实现身份验证、速率限制和正确的错误处理

    ¥Secure your API - Implement authentication, rate limiting, and proper error handling

  • 改进部署 - 为生产环境设置 CI/CD、监控和数据库备份

    ¥Improve deployment - Set up CI/CD, monitoring, and database backups for production

更多信息

¥More info


Stay connected with Prisma

Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:

We genuinely value your involvement and look forward to having you as part of our community!