API 參考文件
Accelerate API 參考文件基於以下 schema
model User {
id Int @id @default(autoincrement())
name String?
email String @unique
}
所有範例皆基於 User
模型。
cacheStrategy
透過 Prisma Client 的 Accelerate 擴充功能,您可以對模型查詢使用 cacheStrategy
參數,並使用 ttl
和 swr
參數來定義 Accelerate 的快取策略。Accelerate 擴充功能要求您安裝 Prisma Client 版本 4.10.0
。
選項
cacheStrategy
參數接受一個具有以下鍵的選項
選項 | 範例 | 類型 | 是否必填 | 描述 |
---|---|---|---|---|
swr | 60 | Int | 否 | 過時重新驗證時間,以秒為單位。 |
ttl | 60 | Int | 否 | 存活時間,以秒為單位。 |
tags | ["user"] | String[] | 否 | tag 作為變數,用於控制應用程式中特定查詢的失效。它是一個可選的字串陣列,用於使快取失效,每個標籤僅包含字母數字字元和底線,且最大長度為 64 個字元。 |
範例
將快取策略添加到查詢中,定義 60 秒的過時重新驗證 (SWR) 值、60 秒的存活時間 (TTL) 值,以及 "emails_with_alice"
的快取標籤
await prisma.user.findMany({
where: {
email: {
contains: "alice@prisma.io",
},
},
cacheStrategy: {
swr: 60,
ttl: 60,
tags: ["emails_with_alice"],
},
});
支援的 Prisma Client 操作
以下是所有支援 cacheStrategy
的讀取查詢操作列表
findUnique()
findUniqueOrThrow()
findFirst()
findFirstOrThrow()
findMany()
count()
aggregate()
groupBy()
cacheStrategy
參數在任何寫入操作(例如 create()
)上皆不受支援。
withAccelerateInfo
任何支援 cacheStrategy
的查詢都可以附加 withAccelerateInfo()
來包裝回應資料,並包含關於 Accelerate 回應的其他資訊。
若要檢索回應的狀態,請使用
const { data, info } = await prisma.user
.count({
cacheStrategy: { ttl: 60, swr: 600 },
where: { myField: 'value' },
})
.withAccelerateInfo()
console.dir(info)
請注意回應物件的 info
屬性。請求資訊儲存在此處。
回傳類型
info
物件的類型為 AccelerateInfo
,並遵循以下介面
interface AccelerateInfo {
cacheStatus: 'ttl' | 'swr' | 'miss' | 'none'
lastModified: Date
region: string
requestId: string
signature: string
}
屬性 | 類型 | 描述 |
---|---|---|
cacheStatus | "ttl" | "swr" | "miss" | "none" | 回應的快取狀態。
|
lastModified | Date | 上次重新整理回應的日期。 |
region | String | 接收請求的資料中心區域。 |
requestId | String | 請求的唯一識別碼。適用於疑難排解。 |
signature | String | Prisma 操作的唯一簽章。 |
$accelerate.invalidate
您可以使用 $accelerate.invalidate
API 使快取失效。
若要按需使快取查詢結果失效,則需要付費方案。每個方案對於每天允許的基於快取標籤的失效次數都有特定限制,儘管呼叫 $accelerate.invalidate
API 本身沒有限制。請參閱我們的定價以了解更多詳細資訊。
範例
若要使以下查詢失效
await prisma.user.findMany({
where: {
email: {
contains: "alice@prisma.io",
},
},
cacheStrategy: {
swr: 60,
ttl: 60,
tags: ["emails_with_alice"],
},
});
您需要在 $accelerate.invalidate
API 中提供快取標籤
try {
await prisma.$accelerate.invalidate({
tags: ["emails_with_alice"],
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
// The .code property can be accessed in a type-safe manner
if (e.code === "P6003") {
console.log(
"The cache invalidation rate limit has been reached. Please try again later."
);
}
}
throw e;
}
每次呼叫最多可以使 5 個標籤失效。
錯誤
Prisma Accelerate 相關錯誤以 P6xxx
開頭。
您可以在此處找到 Prisma Accelerate 的完整錯誤代碼參考。