跳至主要內容

嵌入 Studio

將 Prisma Studio 嵌入至您自己的應用程式

您可以透過 @prisma/studio-core 套件,將 Prisma Studio 嵌入至您自己的應用程式中。

它提供了一個名為 Studio 的 React 元件,可為您的資料庫渲染 Prisma Studio。Studio 元件接受一個執行器 (executor),該執行器會呼叫您後端的 /studio 端點。後端會使用您的 DATABASE_URL(連線字串)來連線至正確的 Prisma Postgres 實例並執行 SQL 查詢。

提示

如果您想看看嵌入式 Studio 的樣子,請**查看 GitHub 上的演示**!

使用案例

您可以在多種情境下將 Prisma Studio 嵌入至您自己的應用程式中:

  • 建立一個用於編輯資料的快速管理儀表板
  • 多租戶 (Multi-tenant) 應用程式,其中每個使用者都有自己的資料庫
  • 為您的使用者提供一種檢視和編輯資料的簡單方法

先決條件

  • 前端:React 應用程式
  • 後端
    • 一個用於公開 /studio 端點的伺服器端應用程式(例如使用 Express 或 Hono)
    • 一個 Prisma Postgres 實例(您可以使用 npx prisma init --db 建立一個)
注意

可嵌入版本的 Prisma Studio 即將與 Prisma ORM 結合,支援其他資料庫。

安裝

安裝 npm 套件

npm install @prisma/studio-core

前端設定

在您的 React 應用程式中,您可以使用 Studio 元件透過 Prisma Studio 渲染資料庫中的表格。它接收一個「執行器」(executor),負責將當前的 SQL 查詢封裝在 HTTP 請求中(同時允許自訂標頭/承載資料),並將其傳送到後端的 /studio 端點。

請參閱 GitHub 上的 演示 以取得完整的參考實作。

最小化實作

以下是最小化實作的樣子

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: "https://:4242/studio",
});

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

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

自訂標頭/承載資料實作

以下是具有自訂標頭/承載資料的實作樣子

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: "https://: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>
);
}

自訂樣式

您可以自訂 Prisma Studio 的外觀,使其符合應用程式的設計。這可以透過將自訂佈景主題傳遞給 Studio 元件來完成。佈景主題只是一組 CSS 變數,用於定義亮色和暗色模式下的顏色、間距和其他樣式屬性。

以下是應用自訂佈景主題的範例

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: "https://:4242/studio",
});
return createPostgresAdapter({ executor });
}, []);

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

透過此設定,Studio 將繼承您的自訂顏色、邊框和字體規則,使其感覺像是您應用程式的一部分,而不是一個獨立的工具。您可以根據所需的自訂程度,定義任意數量的變數。

概念

以下是前端關鍵概念的概述

  • 執行器 (Executor):Studio 與後端之間的橋樑,使用 createStudioBFFClient 函式建立
  • 介面卡 (Adapter):處理 Postgres 特定的查詢格式化
  • 自訂標頭:傳遞身份驗證權杖、使用者資訊等。
  • 自訂承載資料 (Custom payload):隨每個請求傳送額外的上下文/資料

後端設定

您的後端需要公開一個 /studio 端點,供前端發送請求。下方的實作使用 @prisma/studio-core 中的 createPrismaPostgresHttpClient

後端也需要存取 Prisma Postgres API 金鑰,建議將其設為環境變數作為最佳實踐。

請參閱 GitHub 上的 演示 以取得完整的參考實作。

最小化實作

以下是使用 Hono/studio 端點最小化實作。這假設您的連線 URL 可透過 DATABASE_URL 環境變數取得。

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]);
});

自訂標頭/承載資料實作

以下是使用 Hono/studio 端點進階實作。在此情境中,假設是一個多租戶場景,前端會發送一個使用者 ID 和驗證權杖,後端會透過假設的 determineUrlFromContext 函式,利用這些資訊判斷該使用者所屬的 Prisma Postgres 實例。

// 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]);
});

概念

  • 查詢物件:包含來自 Studio 的 SQL 查詢和參數
  • 自訂承載資料:隨每個請求傳送的額外資料
  • Prisma Postgres 用戶端:對您的資料庫執行查詢
  • 錯誤處理:適當地序列化錯誤以供 Studio 顯示

執行流程

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

加入使用者驗證

當您想要針對 Prisma Studio 對應用程式的使用者進行驗證時,可以透過在嵌入式 Prisma Studio 版本周圍加入自訂邏輯來達成。

在前端,建立執行器時務必確保傳遞 Authorization 標頭和其他資料(例如使用者 ID)。

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

在您的伺服器端實作中,您可以從傳入的請求中檢索這些值,並提取該使用者查詢所需的 Prisma Postgres API 金鑰。

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

const userApiKey = await getUserApiKey(userId, token);

授權許可

可嵌入的 Prisma Studio(免費版)採用 Apache 2.0 授權。

✔️ 免費供生產環境使用
⚠️ Prisma 品牌標誌必須保持可見且未經更改
🔐 若要移除我們的品牌標誌或詢問即將推出的合作夥伴專屬功能,請透過此處聯絡我們:partnerships@prisma.io

遙測

此套件包含匿名遙測功能,旨在協助我們改善 Prisma Studio。
使用即表示同意。詳情請參閱我們的隱私權政策

© . This site is unofficial and not affiliated with Prisma Data, Inc.