Skip to main content

嵌入 Studio

将 Prisma Studio 嵌入到你自己的应用中

¥Embed Prisma Studio in your own application

Prisma Studio 可以通过 @prisma/studio-core 包嵌入到你自己的应用中。

¥Prisma Studio can be embedded in your own application via the @prisma/studio-core package.

它提供 Studio,这是一个 React 组件,用于为你的数据库渲染 Prisma Studio。Studio 组件接受一个执行器,该执行器调用你后端的 /studio 端点。后端使用你的 DATABASE_URL(连接字符串)连接到正确的 Prisma Postgres 实例并执行 SQL 查询。

¥It provides Studio, a React component which renders Prisma Studio for your database. The Studio component accepts an executor that calls a /studio endpoint in your backend. The backend uses your DATABASE_URL (connection string) to connect to the correct Prisma Postgres instance and execute the SQL query.

提示

如果你想查看嵌入式 Studio 的外观,请访问 GitHub 上的 查看演示

¥If you want to see what embedded Studio looks like, check out the demo on GitHub!

用例

¥Use cases

你可以在各种情况下将 Prisma Studio 嵌入到你自己的应用中:

¥You can embed Prisma Studio in your own app in various scenarios:

  • 创建一个用于编辑数据的快速管理仪表板

    ¥Create an quick admin dashboard for editing data

  • 多租户应用,每个用户都有自己的数据库

    ¥Multi-tenant application where every user has their own DB

  • 为你的用户提供一种查看和编辑数据的简便方法

    ¥Provide an easy way to view and edit data to your users

先决条件

¥Prerequisites

  • 前端:一个 React 应用

    ¥Frontend: A React application

  • 后端:

    ¥Backend:

    • 一个用于公开 /studio 端点的服务器端应用(例如使用 Express 或 Hono)

      ¥A server-side application to expose the /studio endpoint (e.g. with Express or Hono)

    • 一个 Prisma Postgres 实例(你可以使用 npx prisma init --db 创建一个)

      ¥A Prisma Postgres instance (you can create one with npx prisma init --db)

注意

Prisma Studio 的可嵌入版本将很快与 Prisma ORM 结合用于其他数据库。

¥The embeddable version of Prisma Studio will be available for other databases in combination with Prisma ORM soon.

安装

¥Installation

安装 npm 包:

¥Install the npm package:

npm install @prisma/studio-core

前端设置

¥Frontend setup

在你的 React 应用中,你可以使用 Studio 组件通过 Prisma Studio 渲染数据库中的表。它接收一个执行器,该执行器负责将当前 SQL 查询打包成 HTTP 请求(也允许自定义标头/负载),并将其发送到后端的 /studio 端点。

¥In your React app, you can use the Studio component to render the tables in your database via Prisma Studio. It receives an executor which is responsible for packaging the current SQL query in an HTTP request (also allowing for custom headers/payloads) and sending it to the /studio endpoint in your backend.

查看 GitHub 上的 demo 以获取完整的参考实现。

¥Check out the demo on GitHub for a full reference implementation.

最小实现

¥Minimal implementation

以下是最小实现的样子:

¥Here's what a minimal implementation looks like:

import { Studio } from "@prisma/studio-core/ui";
import { createPostgresAdapter } from "@prisma/studio-core/data/postgres-core";
import { createStudioBFFClient } from "@prisma/studio-core/data/bff";
import "@prisma/studio-core/ui/index.css"

function App() {
const adapter = useMemo(() => {
// 1. Create a client that points to your backend endpoint
const executor = createStudioBFFClient({
url: "http://localhost:4242/studio",
});

// 2. Create a Postgres adapter with the executor
const adapter = createPostgresAdapter({ executor });
return adapter;
}, []);

return (
<Layout>
<Studio adapter={adapter} />
</Layout>
);
}

自定义标头/负载实现

¥Custom headers/payload implementation

使用自定义标头/有效负载的实现如下所示:

¥Here's what an implementation with custom headers/payload looks like:

import { Studio } from "@prisma/studio-core/ui";
import { createPostgresAdapter } from "@prisma/studio-core/data/postgres-core";
import { createStudioBFFClient } from "@prisma/studio-core/data/bff";
import "@prisma/studio-core/ui/index.css"

function App() {
const adapter = useMemo(() => {
// 1. Create a client that points to your backend endpoint
const executor = createStudioBFFClient({
url: "http://localhost:4242/studio",
customHeaders: {
"X-Custom-Header": "example-value", // Pass any custom headers
},
customPayload: {
customValue: "example-value" // Pass any custom data
}
});

// 2. Create a Postgres adapter with the executor
const adapter = createPostgresAdapter({ executor });
return adapter;
}, []);

return (
<Layout>
<Studio adapter={adapter} />
</Layout>
);
}

自定义样式

¥Custom styling

你可以自定义 Prisma Studio 的外观,使其与你的应用设计相匹配。这是通过将自定义主题传递给 Studio 组件来实现的。主题只是一组 CSS 变量,用于定义明夜间模式下的颜色、间距和其他样式属性。

¥You can customize the look and feel of Prisma Studio so that it matches your application’s design. This is done by passing a custom theme to the Studio component. A theme is simply a set of CSS variables that define colors, spacing, and other style properties for both light and dark modes.

以下是应用自定义主题的示例:

¥Here's an example of applying a custom theme:

import { Studio } from "@prisma/studio-core/ui";
import { createPostgresAdapter } from "@prisma/studio-core/data/postgres-core";
import { createStudioBFFClient } from "@prisma/studio-core/data/bff";
import "@prisma/studio-core/ui/index.css";

const customTheme = `
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 20 14.3% 4.1%;
--primary: 47.9 95.8% 53.1%;
--primary-foreground: 26 83.3% 14.1%;
--border: 20 5.9% 90%;
--input: 20 5.9% 90%;
--ring: 20 14.3% 4.1%;
--radius: 0rem;
}

.dark {
--background: 20 14.3% 4.1%;
--foreground: 60 9.1% 97.8%;
--primary: 47.9 95.8% 53.1%;
--primary-foreground: 26 83.3% 14.1%;
--border: 12 6.5% 15.1%;
--input: 12 6.5% 15.1%;
--ring: 35.5 91.7% 32.9%;
}
}
`;

function App() {
const adapter = useMemo(() => {
const executor = createStudioBFFClient({
url: "http://localhost:4242/studio",
});
return createPostgresAdapter({ executor });
}, []);

return (
<Layout>
<Studio theme={customTheme} adapter={adapter} />
</Layout>
);
}

使用此设置,Studio 会继承你的自定义颜色、边框和排版规则,使其感觉像是应用的自然组成部分,而不是一个单独的工具。你可以根据所需的自定义级别定义任意数量的变量。

¥With this setup, Studio inherits your custom colors, borders, and typography rules, making it feel like a natural part of your app rather than a separate tool. You can define as many or as few variables as you need depending on the level of customization you want.

概念

¥Concepts

以下是前端关键概念的概述:

¥Here's an overview of the key concepts in your frontend:

  • 执行器:Studio 和后端之间的桥梁,它是使用 createStudioBFFClient 函数创建的。

    ¥Executor: The bridge between Studio and your backend, it's created using the createStudioBFFClient function

  • 适配器:处理 Postgres 特定的查询格式

    ¥Adapter: Handles Postgres-specific query formatting

  • 自定义标头:传递身份验证令牌、用户信息等。

    ¥Custom headers: Pass authentication tokens, user info, etc.

  • 自定义有效负载:每次请求时发送额外的上下文/数据

    ¥Custom payload: Send additional context/data with each request

后端设置

¥Backend setup

你的后端需要公开一个 /studio 端点,前端会将请求发送到该端点。以下实现使用了 @prisma/studio-core 中的 createPrismaPostgresHttpClient

¥Your backend needs to expose a /studio endpoint where the frontend sends its requests. The implementation below uses createPrismaPostgresHttpClient from @prisma/studio-core.

后端还需要访问 Prisma Postgres API 密钥,我们建议将其设置为环境变量,这是最佳实践。

¥The backend also needs to have access to the Prisma Postgres API key, we recommend setting it as an environment variable as a best practice.

查看 GitHub 上的 demo 以获取完整的参考实现。

¥Check out the demo on GitHub for a full reference implementation.

最小实现

¥Minimal implementation

以下是 /studio 端点在 Hono 中的最小实现。这假设你的连接 URL 可通过 DATABASE_URL 环境变量访问:

¥Here's what a minimal implementation for the /studio endpoint looks like with Hono. This assumes that your connection URL is available via the DATABASE_URL env var:

import { Hono } from "hono";
import { createPrismaPostgresHttpClient } from "@prisma/studio-core/data/ppg";
import { serializeError } from "@prisma/studio-core/data/bff";

const app = new Hono().use("*", cors());

app.post("/studio", async (c) => {
// 1. Extract the query and custom data from the request
const { query } = await c.req.json();

// 2. Read DB URL from env vars
const url = process.env.DATABASE_URL;

// 3. Execute the query against Prisma Postgres
const [error, results] = await createPrismaPostgresHttpClient({ url }).execute(query);

// 6. Return results or errors
if (error) {
return c.json([serializeError(error)]);
}

return c.json([null, results]);
});

自定义标头/负载实现

¥Custom headers/payload implementation

以下是 /studio 端点在 Hono 中的稍微高级一点的实现。在本例中,假设存在一个多租户场景,前端发送用户 ID 和身份验证令牌,后端使用该令牌通过假设的 determineUrlFromContext 函数确定属于该用户的 Prisma Postgres 实例:

¥Here's what a slightly more advanced implementation for the /studio endpoint looks like with Hono. In this case, a multi-tenant scenario is assumed where the frontend sends over a user ID and authentication token which is used on the backend to determine the Prisma Postgres instance that belongs to that user via a hypothetical determineUrlFromContext function:

// server/index.ts
import { Hono } from "hono";
import { createPrismaPostgresHttpClient } from "@prisma/studio-core/data/ppg";
import { serializeError } from "@prisma/studio-core/data/bff";

const app = new Hono().use("*", cors());

app.post("/studio", async (c) => {
// 1. Extract the query and custom data from the request
const { query, customPayload } = await c.req.json();

// 2. Access custom headers (great for auth!)
const customHeader = c.req.header("X-Custom-Header");
console.log("Received headers:", { customHeader });

// 3. Use custom payload data
console.log("Received value:", customPayload.customValue);

// 4. Determine the URL (this is where you'd implement your auth logic)
const url = determineUrlFromContext(customHeader, customPayload);

// 5. Execute the query using Prisma Postgres or Prisma Accelerate
const [error, results] = await createPrismaPostgresHttpClient({ url }).execute(query);

// 6. Return results or errors
if (error) {
return c.json([serializeError(error)]);
}

return c.json([null, results]);
});

概念

¥Concepts

  • 查询对象:包含 Studio 中的 SQL 查询和参数

    ¥Query object: Contains the SQL query and parameters from Studio

  • 自定义有效负载:每次请求发送的附加数据

    ¥Custom payload: Additional data sent with each request

  • Prisma Postgres 客户端:针对你的数据库执行查询

    ¥Prisma Postgres client: Executes queries against your database

  • 错误处理:正确序列化错误以便 Studio 显示

    ¥Error handling: Properly serialize errors for Studio to display

执行流程

¥Execution flow

以下是嵌入式 Prisma Studio 版本中执行流程的概述:

¥Here's an overview of the execution flow in your embedded Prisma Studio version:

添加用户身份验证

¥Adding user authentication

当你想使用 Prisma Studio 对应用用户进行身份验证时,你可以通过在嵌入式 Prisma Studio 版本周围添加自定义逻辑来实现。

¥When you want to authenticate the users of your app against Prisma Studio, you can do that by adding custom logic around your embedded Prisma Studio version.

在前端,你可以确保在创建执行器时传递 Authorization 标头和其他数据(例如用户 ID):

¥On the frontend, you can ensure to pass the Authorization header and other data (e.g. a user ID) when creating the executor:

const executor = createStudioBFFClient({
url: "http://localhost:4242/studio",
customHeaders: {
"X-User-ID": currentUser.id,
"Authorization": `Bearer ${userToken}`,
},
});

在你的服务器端实现中,你可以从传入的请求中检索这些值,并提取此用户查询所需的 Prisma Postgres API 密钥:

¥In your server-side implementation, you can then retrieve these values from the incoming request and extract the Prisma Postgres API key that's needed for this user's query:

const userId = c.req.header("X-User-ID");
const token = c.req.header("Authorization");

const userApiKey = await getUserApiKey(userId, token);

许可

¥Licensing

Embeddable Prisma Studio(免费)已获得 Apache 2.0 许可。

¥Embeddable Prisma Studio (Free) is licensed under Apache 2.0.

✔️ 免费用于生产环境 ⚠️ Prisma 品牌标识必须保持可见且不可更改 🔐 如需移除我们的品牌标识或咨询即将推出的合作伙伴专属功能,请点击此处联系我们:partnerships@prisma.io

¥✔️ Free for production use\ ⚠️ Prisma branding must remain visible and unaltered\ 🔐 To remove our branding or to inquire about upcoming partner-only features, ping us here: partnerships@prisma.io

遥测

¥Telemetry

此软件包包含匿名遥测数据,以帮助我们改进 Prisma Studio。使用即表示同意。在我们的 隐私政策 中了解更多信息。

¥This package includes anonymized telemetry to help us improve Prisma Studio.\ Use implies consent. Learn more in our Privacy Policy.