Skip to main content

API 参考

Accelerate API 参考文档基于以下架构:

¥The Accelerate API reference documentation is based on the following schema:

model User {
id Int @id @default(autoincrement())
name String?
email String @unique
}

所有示例均基于 User 模型。

¥All example are based on the User model.

cacheStrategy

使用 Prisma 客户端的 Accelerate 扩展,你可以使用 cacheStrategy 参数进行模型查询,并使用 ttlswr 参数定义 Accelerate 的缓存策略。Accelerate 扩展需要你安装 Prisma 客户端版本 4.10.0

¥With the Accelerate extension for Prisma Client, you can use the cacheStrategy parameter for model queries and use the ttl and swr parameters to define a cache strategy for Accelerate. The Accelerate extension requires that you install Prisma Client version 4.10.0.

选项

¥Options

cacheStrategy 参数接受一个包含以下键的选项:

¥The cacheStrategy parameter takes an option with the following keys:

选项示例类型必需的描述
swr60Intstale-while-revalidate 时间(以秒为单位)。
ttl60Int生存时间(秒)。
tags["user"]String[]tag 用作变量,用于控制应用中特定查询的失效。它是一个可选的字符串数组,用于 invalidate 缓存,每个标签仅包含字母数字字符和下划线,最大长度为 64 个字符。

示例

¥Examples

为查询添加缓存策略,定义 60 秒的重新验证时过期时间 (SWR) 值、60 秒的生存时间 (TTL) 值以及 "emails_with_alice" 的缓存标签:

¥Add a caching strategy to the query, defining a 60-second stale-while-revalidate (SWR) value, a 60-second time-to-live (TTL) value, and a cache tag of "emails_with_alice":

await prisma.user.findMany({
where: {
email: {
contains: "alice@prisma.io",
},
},
cacheStrategy: {
swr: 60,
ttl: 60,
tags: ["emails_with_alice"],
},
});

支持的 Prisma 客户端操作

¥Supported Prisma Client operations

以下是所有支持 cacheStrategy 的读取查询操作的列表:

¥The following is a list of all read query operations that support cacheStrategy:

info

任何写入操作(例如 create())都不支持 cacheStrategy 参数。

¥The cacheStrategy parameter is not supported on any write operations, such as create().

withAccelerateInfo

任何支持 cacheStrategy 的查询都可以附加 withAccelerateInfo() 来封装响应数据,并包含有关 Accelerate 响应的其他信息。

¥Any query that supports the cacheStrategy can append withAccelerateInfo() to wrap the response data and include additional information about the Accelerate response.

要检索响应状态,请使用:

¥To retrieve the status of the response, use:

const { data, info } = await prisma.user
.count({
cacheStrategy: { ttl: 60, swr: 600 },
where: { myField: 'value' },
})
.withAccelerateInfo()

console.dir(info)
info

请注意响应对象的 info 属性。这是存储请求信息的地方。

¥Notice the info property of the response object. This is where the request information is stored.

返回类型

¥Return type

info 对象属于 AccelerateInfo 类型,并遵循以下接口:

¥The info object is of type AccelerateInfo and follows the interface below:

interface AccelerateInfo {
cacheStatus: 'ttl' | 'swr' | 'miss' | 'none'
lastModified: Date
region: string
requestId: string
signature: string
}
属性类型描述
cacheStatus"ttl" | "swr" | "miss" | "none" 响应的缓存状态
  • ttl indicates a cache hit within the ttl duration and no database query was executed
  • swr indicates a cache hit within the swr duration and the data is being refreshed by Accelerate in the background
  • miss indicates that both ttl and swr have expired and the database query was executed by the request
  • none indicates that no cache strategy was specified and the database query was executed by the request
lastModifiedDate上次刷新响应的日期。
regionString接收请求的数据中心区域。
requestIdString请求的唯一标识符。有助于故障排除。
signatureStringPrisma 操作的唯一签名。

$accelerate.invalidate

你可以使用 $accelerate.invalidate API 使缓存失效。

¥You can invalidate the cache using the $accelerate.invalidate API.

注意

要按需使缓存的查询结果无效,需要付费计划。每个计划对每天允许的基于缓存标签的失效次数都有特定的限制,但调用 $accelerate.invalidate API 本身没有限制。请参阅我们的 更多定价详情

¥To invalidate cached query results on-demand, a paid plan is required. Each plan has specific limits on the number of cache tag-based invalidations allowed per day, though there are no limits on calling the $accelerate.invalidate API itself. See our pricing for more details.

示例

¥Example

要使以下查询无效:

¥To invalidate the query below:

await prisma.user.findMany({
where: {
email: {
contains: "alice@prisma.io",
},
},
cacheStrategy: {
swr: 60,
ttl: 60,
tags: ["emails_with_alice"],
},
});

你需要在 $accelerate.invalidate API 中提供缓存标签:

¥You need to provide the cache tag in the $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 个标签失效。

¥You can invalidate up to 5 tags per call.

$accelerate.invalidateAll

你可以使用 $accelerate.invalidateAll API 使整个缓存失效。

¥You can invalidate the entire cache using the $accelerate.invalidateAll API.

示例

¥Example

要使以下查询无效:

¥To invalidate the query below:

await prisma.user.findMany({
where: {
email: {
contains: "alice@prisma.io",
},
},
cacheStrategy: {
swr: 60,
ttl: 60,
tags: ["emails_with_alice"],
},
});

只需调用 $accelerate.invalidateAll API:

¥Just call the $accelerate.invalidateAll API:

try {
await prisma.$accelerate.invalidateAll();
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === "P6003") {
console.log(
"The cache invalidation rate limit has been reached. Please try again later."
);
}
}
throw e;
}

为什么要使用 $accelerate.invalidateAll

¥Why use $accelerate.invalidateAll?

invalidate("all") 等替代方案相比,此方法提供更好的编辑器支持(例如 IntelliSense)。

¥This method offers better editor support (e.g. IntelliSense) than alternatives like invalidate("all").

警告

这将清除整个环境的缓存 - 请谨慎使用。

¥This clears cache for the entire environment—use with care.

提供自定义获取实现

¥Providing a Custom Fetch Implementation

从 Accelerate 2.0.0 版本开始,你可以在使用 Accelerate 扩展 Prisma 客户端时提供自定义的 fetch 函数实现。这使你能够更灵活地控制 HTTP 请求在应用中的处理方式。

¥Starting from Accelerate version 2.0.0, you can provide a custom implementation of the fetch function when extending the Prisma Client with Accelerate. This allows you greater flexibility and control over how HTTP requests are handled within your application.

要传递自定义 fetch 实现,你可以使用以下模式:

¥To pass a custom fetch implementation, you can use the following pattern:

const myFetch = (input: URL, init?: RequestInit): Promise<Response> => {
// Your custom fetch logic here
return fetch(input, init);
};

const prisma = new PrismaClient().$extends(withAccelerate({ fetch: myFetch }));

错误

¥Errors

与 Prisma Accelerate 相关的错误以 P6xxx 开头。

¥Prisma Accelerate-related errors start with P6xxx.

你可以找到 Prisma Accelerate 此处 的完整错误代码参考。

¥You can find the full error code reference for Prisma Accelerate here.