// file: app/lib/server/prismaMiddleware.ts
import { Prisma } from '@prisma/client';
import { PrismaClient } from '@prisma/client/edge';
import { withAccelerate } from '@prisma/extension-accelerate';
// Dynamically update lastModifiedTimestamp for the `memory` model.
const memoryExtension = Prisma.defineExtension({
name: 'memoryExtension',
model: {
memory: {
async $before(operation, args, next) {
if (operation === 'create' || operation === 'update' || operation === 'updateMany') {
if (!args.data) {
args.data = {};
}
args.data.lastModifiedTimestamp = Date.now();
}
return await next(args);
},
},
},
});
// Cache strategy extension to set a default TTL for relevant queries
const cacheStrategyExtension = Prisma.defineExtension({
name: 'cacheStrategyExtension',
query: {
$allModels: {
async $before(operation, args, next) {
if (
operation === 'findMany' ||
operation === 'findUnique' ||
operation === 'findFirst' ||
operation === 'aggregate' ||
operation === 'groupBy'
) {
if (!args.cacheStrategy) {
args.cacheStrategy = {
ttl: 60,
swr: 60
}; // Default cacheStrategy
}
}
return await next(args);
},
},
},
});
// Initialize Prisma Client with extensions
export const prisma = new PrismaClient({
log: ['query', 'info', 'warn', 'error']
})
.$extends(withAccelerate())
// .$extends(memoryExtension)
.$extends(cacheStrategyExtension);
export default prisma;