|
1 | 1 | import { PrismaClient, Prisma } from '../prisma/generated/client'; |
2 | 2 |
|
3 | 3 | /** |
4 | | - * Creates a Prisma client instance for the finance database |
| 4 | + * Write operations that should be blocked on the readonly client |
| 5 | + */ |
| 6 | +const BLOCKED_WRITE_OPERATIONS = [ |
| 7 | + 'create', |
| 8 | + 'createMany', |
| 9 | + 'update', |
| 10 | + 'updateMany', |
| 11 | + 'upsert', |
| 12 | + 'delete', |
| 13 | + 'deleteMany', |
| 14 | +] as const; |
| 15 | + |
| 16 | +/** |
| 17 | + * Creates a read-only Prisma client instance for the finance database. |
| 18 | + * This client only allows read operations (findMany, findFirst, findUnique, count, aggregate, etc.). |
| 19 | + * Write operations (create, update, delete, etc.) will throw an error. |
| 20 | + * |
5 | 21 | * @param connectionString - Database connection string |
6 | 22 | * @param options - Optional Prisma client options (logging, transaction timeout, etc.) |
7 | | - * @returns Configured PrismaClient instance |
| 23 | + * @returns Configured read-only PrismaClient instance |
8 | 24 | */ |
9 | 25 | export function createFinancePrismaClient( |
10 | 26 | connectionString: string, |
11 | 27 | options?: Omit<Prisma.PrismaClientOptions, 'datasources'> |
12 | 28 | ): PrismaClient { |
13 | | - return new PrismaClient({ |
| 29 | + const client = new PrismaClient({ |
14 | 30 | ...options, |
15 | 31 | datasources: { |
16 | 32 | db: { |
17 | 33 | url: connectionString, |
18 | 34 | }, |
19 | 35 | }, |
20 | 36 | }); |
| 37 | + |
| 38 | + // Use Prisma middleware to block write operations |
| 39 | + // Type assertion needed because $use may not be in the type definition |
| 40 | + (client as any).$use(async (params: any, next: any) => { |
| 41 | + // Check if this is a write operation |
| 42 | + if (BLOCKED_WRITE_OPERATIONS.includes(params.action)) { |
| 43 | + throw new Error( |
| 44 | + `Write operation '${params.model}.${params.action}' is not allowed on read-only finance Prisma client. ` + |
| 45 | + 'This client only supports read operations (findMany, findFirst, findUnique, count, aggregate, groupBy, etc.).' |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + // Allow read operations and other allowed operations |
| 50 | + return next(params); |
| 51 | + }); |
| 52 | + |
| 53 | + return client; |
21 | 54 | } |
22 | 55 |
|
23 | 56 | // Re-export Prisma types and enums for use in consuming applications |
|
0 commit comments