Install the Prisma Extension:
npm install prisma-redis-cache
Configure the extension:
import {PrismaClient} from "@prisma/client"
import {env} from "node:process"
import configureCache from "prisma-redis-cache"
import {createClient} from "redis"
const redis = await createClient({
url: env.REDIS_CONNECTION_URL
}).connect()
const prisma = new PrismaClient().$extends(
configureCache({
redisClient: redis
})
)
Example usage:
const user = await prisma.user.findUnique({
where: {
username: "Gabriel"
},
select: {
username: true,
email: true,
password: true
},
// ˅˅ - The per-operation caching options
cache: {
// | A unique key for the cache.
// ˅ The key is automatically prefixed with the model name to avoid overlaps.
key: `Gabriel`,
// ˅ The time-to-live of the cache, in seconds **/
ttl: 60 * 15
}
})
That's it! You can start caching your Prisma operations right away 🎉
Note
The extension has JSDoc documentation and supports IDE auto-completion. All Prisma operations except raw queries can interact with the cache.
await prisma.user.create({
data: {
username: "user",
email: "[email protected]",
password: "TheHashedUserPassword"
},
select: {
username: true,
email: true,
password: true
},
cache: {
key: `user`,
ttl: 60 * 60
}
})
await prisma.user.update({
where: {
username: "user"
},
data: {
email: "[email protected]"
},
select: {
username: true,
email: true,
password: true
},
cache: {
key: `user`,
// ˅ Whether to update or evict the cache
update: true,
ttl: 60 * 60
}
})
await prisma.user.delete({
where: {
username: "user"
},
cache: {
key: `user`
}
})