部署到 Deno 部署
通过本指南,你可以了解如何构建简单的应用并将其部署到 Deno 部署。应用使用 Prisma ORM 将每个请求的日志保存到 Prisma Postgres 数据库。
¥With this guide, you can learn how to build and deploy a simple application to Deno Deploy. The application uses Prisma ORM to save a log of each request to a Prisma Postgres database.
本指南涵盖了 Prisma CLI 与 Deno CLI、Deno Deploy、Prisma Client 和 Prisma Postgres 的使用。
¥This guide covers the use of Prisma CLI with Deno CLI, Deno Deploy, Prisma Client, and Prisma Postgres.
本指南演示了如何将应用与 Prisma Postgres 数据库一起部署到 Deno Deploy,但你也可以使用 使用 Prisma Accelerate 的你自己的数据库。
¥This guide demonstrates how to deploy an application to Deno Deploy in conjunction with a Prisma Postgres database, but you can also use your own database with Prisma Accelerate.
先决条件
¥Prerequisites
-
一个免费的 账户
¥a free account
-
一个免费的 Deno 部署 账户
¥a free Deno Deploy account
-
Node.js 和 npm 安装
¥Node.js & npm installed
-
安装 Deno v1.29.4 或更高版本。了解更多。
¥Deno v1.29.4 or later installed. Learn more.
-
(受到推崇的)Prisma ORM 的最新版本。
¥(Recommended) Latest version of Prisma ORM.
-
(受到推崇的)VS Code 的 Deno 扩展。了解更多。
¥(Recommended) Deno extension for VS Code. Learn more.
1. 设置你的应用和数据库
¥ Set up your application and database
首先,为你的项目创建一个目录,然后使用 deno run
来初始化你的应用,并使用 prisma init
作为 带有 npm 说明符的 npm 包。
¥To start, you create a directory for your project, and then use deno run
to initialize your application with prisma init
as an npm package with npm specifiers.
要设置你的应用,请打开你的终端并导航到你选择的位置。然后,运行以下命令来设置你的应用:
¥To set up your application, open your terminal and navigate to a location of your choice. Then, run the following commands to set up your application:
mkdir prisma-deno-deploy
cd prisma-deno-deploy
npx prisma@latest init --db
输入项目名称并选择数据库区域。
¥Enter a name for your project and choose a database region.
这个命令:
¥This command:
-
将你的 CLI 连接到你的 账户。如果你未登录或没有账户,你的浏览器将打开以指导你创建新账户或登录现有账户。
¥Connects your CLI to your account. If you're not logged in or don't have an account, your browser will open to guide you through creating a new account or signing into your existing one.
-
为你的数据库模型创建一个包含
schema.prisma
文件的prisma
目录。¥Creates a
prisma
directory containing aschema.prisma
file for your database models. -
使用你的
DATABASE_URL
创建.env
文件(例如,对于 Prisma Postgres,它应该具有类似于DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..."
的内容)。¥Creates a
.env
file with yourDATABASE_URL
(e.g., for Prisma Postgres it should have something similar toDATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..."
).
编辑 prisma/schema.prisma
文件以定义 Log
模型,添加自定义 output
路径和 prisma-client
生成器,并将 deno
作为 runtime
:
¥Edit the prisma/schema.prisma
file to define a Log
model, add a custom output
path and the prisma-client
generator with deno
as the runtime
:
generator client {
provider = "prisma-client-js"
provider = "prisma-client"
output = "../generated/prisma"
runtime = "deno"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Log {
id Int @id @default(autoincrement())
level Level
message String
meta Json
}
enum Level {
Info
Warn
Error
}
然后,安装 Prisma 客户端:
¥Then, install Prisma Client:
deno install npm:@prisma/client
然后,安装使用 Prisma Postgres 所需的 客户端扩展:
¥Then, install the Client extension required to use Prisma Postgres:
deno install npm:@prisma/extension-accelerate
Prisma Client 在 Deno 上默认不读取 .env
文件,因此你还必须在本地安装 dotenv-cli
:
¥Prisma Client does not read .env
files by default on Deno, so you must also install dotenv-cli
locally:
deno install npm:dotenv-cli
2. 创建数据库架构
¥ Create the database schema
数据模型就位并配置数据库连接后,你现在可以将数据模型应用到数据库。
¥With the data model in place and your database connection configured, you can now apply the data model to your database.
deno run -A npm:prisma migrate dev --name init
该命令做了两件事:
¥The command does two things:
-
它为此迁移创建一个新的 SQL 迁移文件
¥It creates a new SQL migration file for this migration
-
它针对数据库运行 SQL 迁移文件
¥It runs the SQL migration file against the database
此时,该命令具有额外的副作用。该命令安装 Prisma Client 并为项目创建 package.json
文件。
¥At this point, the command has an additional side effects. The command installs Prisma Client and creates the package.json
file for the project.
3. 创建你的应用
¥ Create your application
你现在可以创建本地 Deno 应用。在项目根文件夹中创建 index.ts
并添加以下内容:
¥You can now create a local Deno application. Create index.ts
in the root folder of your project and add the content below:
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";
import { withAccelerate } from "npm:@prisma/extension-accelerate";
import { PrismaClient } from "./generated/prisma/client.ts";
const prisma = new PrismaClient().$extends(withAccelerate());
async function handler(request: Request) {
// Ignore /favicon.ico requests:
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" },
});
}
serve(handler);
VS Code 错误:An import path cannot end with a '.ts' extension
¥VS Code error: An import path cannot end with a '.ts' extension
如果你使用 VS Code 并看到 index.ts
开头的 import
语句出现错误 An import path cannot end with a '.ts' extension
,则需要安装 VS Code 的 Deno 扩展,选择 View > Command Palette 并运行命令 Deno:初始化工作区配置。这告诉 VS Code 当前项目中的 TypeScript 文件需要使用 Deno 运行,然后触发正确的验证。
¥If you use VS Code and see the error An import path cannot end with a '.ts' extension
for the import
statements at the beginning of index.ts
, you need to install the Deno extension for VS Code, select View > Command Palette and run the command Deno: Initialize Workspace Configuration. This tells VS Code that the TypeScript files in the current project need to run with Deno, which then triggers the correct validations.
4. 在本地测试你的应用
¥ Test your application locally
你现在可以在本地启动应用并测试日志条目的创建。
¥You can now start your application locally and test the creation of log entries.
npx dotenv -- deno run -A ./index.ts
在 Web 浏览器中,打开 http://localhost:8000/。此页面将你的请求写入数据库。
¥In a web browser, open http://localhost:8000/. This page writes your request to the database.
{
"id": 1,
"level": "Info",
"message": "GET http://localhost:8000/",
"meta": {
"headers": "{}"
}
}
重新加载页面几次。
每次重新加载时,脚本都会生成一个新的日志条目,并且当前日志条目的 id
会增加。
¥Reload the page a few times.
Every time you reload, the script generates a new log entry and the id
of the current log entry increments.
这确认你的应用在你从本地环境运行时可以正常工作。
¥This confirms that your application works when you run it from your local environment.
5. 创建存储库并推送到 GitHub
¥ Create a repository and push to GitHub
你需要一个 GitHub 存储库来将项目添加到 Deno Deploy,并在推送更改时启用自动部署。
¥You need a GitHub repository to add your project to Deno Deploy and enable automated deployments whenever you push changes.
要设置 GitHub 存储库:
¥To set up a GitHub repository:
-
使用以下命令在本地初始化存储库并将更改推送到 GitHub:
¥Initialize your repository locally and push your changes to GitHub, with the following commands:
git init -b main
git remote add origin https://github.com/<username>/prisma-deno-deploy
git add .
git commit -m "initial commit"
git push -u origin main
6. 部署到 Deno 部署
¥ Deploy to Deno Deploy
使用 GitHub 存储库将你的应用添加到 Deno Deploy:
¥Use the GitHub repository to add your application to Deno Deploy:
-
¥Go to https://dash.deno.com/.
-
选择 GitHub 组织或用户,然后选择存储库。
¥Select a GitHub organization or user and then select a repository.
-
选择一个生产分支并选择 Fresh(自动)模式,以便每次将更改推送到存储库时 Deno Deploy 都可以部署。
¥Select a production branch and select Fresh (Automatic) mode so that Deno Deploy can deploy every time you push a change to the repository.
-
在构建步骤中添加
deno run -A npm:prisma generate
以生成 Prisma 客户端。¥In the Build Step add
deno run -A npm:prisma generate
to generate the Prisma Client. -
选择
index.ts
作为项目的入口点。¥Select
index.ts
as the entry point to your project. -
单击
Create & Deploy
。¥Click
Create & Deploy
.
部署应该会失败,因为你必须添加 DATABASE_URL
环境变量。
¥The deployment should fail as you have to add the DATABASE_URL
environment variable.
找到并导航到项目的设置。
¥Locate and navigate to the settings for the project.
-
要定义数据库连接字符串,请单击环境变量部分中的添加变量。
¥To define the database connection string, click Add Variable in the Environment Variables section.
-
对于密钥,输入
DATABASE_URL
。¥For KEY, enter
DATABASE_URL
. -
对于 VALUE,粘贴数据库连接字符串。
¥For VALUE, paste the database connection string.
-
-
单击保存。
¥Click Save.
你必须添加一些代码并创建另一个提交以触发重新部署。
¥You have to add some code and create another commit to trigger a re-dployment.
在你的 index.ts
文件中添加以下代码:
¥Add the following code in your index.ts
file:
import { serve } from "https://deno.land/std@0.140.0/http/server.ts";
import { withAccelerate } from "npm:@prisma/extension-accelerate";
import { PrismaClient } from "./generated/prisma/client.ts";
const prisma = new PrismaClient().$extends(withAccelerate());
async function handler(request: Request) {
// Ignore /favicon.ico requests:
const url = new URL(request.url);
if (url.pathname === "/favicon.ico") {
return new Response(null, { status: 204 });
}
console.log("Request received.")
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" },
});
}
serve(handler);
提交新的更改:
¥Commit the new changes:
git add .
git commit -m "add log"
git push origin main
这将重建部署,由于已添加环境变量,部署现在可以正常工作。完成后,请按照部署输出中的 URL 进行操作。应用应显示与之前相同的结果,但带有新的递增日志记录 ID:
¥This rebuilds the deployment, which now works because the environment variable has been added. After it completes, follow the URL in the deployment output. The application should show the same result as before, with a new, incremented log record ID:
{
"id": 5,
"level": "Info",
"message": "GET https://prisma-deno-deploy.deno.dev/",
"meta": {
"headers": "{}"
}
}
概括
¥Summary
你已成功部署在 TypeScript 中创建的 Deno 应用,该应用使用 Prisma Client 连接到 Prisma Postgres 数据库。
¥You successfully deployed a Deno application that you created in TypeScript, which uses Prisma Client connecting to a Prisma Postgres database.