|
| 1 | +import { Prisma } from '@prisma/client' |
| 2 | +import { Logger } from '@config/logger.config'; |
| 3 | + |
| 4 | +const logger = new Logger('PGPATH2MYSQL'); |
| 5 | + |
| 6 | +function convertPgPathToMysql (path) { |
| 7 | + if (!Array.isArray(path)) return path |
| 8 | + let result = '$' |
| 9 | + for (const item of path) { |
| 10 | + if (/^\d+$/.test(item)) { |
| 11 | + result += `[${item}]` |
| 12 | + } else { |
| 13 | + result += `.${item}` |
| 14 | + } |
| 15 | + } |
| 16 | + return result |
| 17 | +} |
| 18 | + |
| 19 | +function processWhere (obj) { |
| 20 | + if (obj && typeof obj === 'object') { |
| 21 | + for (const key in obj) { |
| 22 | + if (Object.prototype.hasOwnProperty.call(obj, key)) { |
| 23 | + if (key === 'path') { |
| 24 | + obj[key] = convertPgPathToMysql(obj[key]); |
| 25 | + } else { |
| 26 | + processWhere(obj[key]); |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// https://www.prisma.io/docs/orm/prisma-client/client-extensions/query#modify-all-operations-in-all-models-of-your-schema |
| 34 | +// https://www.prisma.io/docs/orm/prisma-client/client-extensions/query#modify-a-specific-operation-in-a-specific-model |
| 35 | + |
| 36 | +const overriddenOperation = async ({ model, operation, args, query }) => { |
| 37 | + if (args?.where) { |
| 38 | + processWhere(args.where) |
| 39 | + } |
| 40 | + const result = await query(args) |
| 41 | + logger.debug({ model, operation, args: JSON.stringify(args), result }) |
| 42 | + return result |
| 43 | +} |
| 44 | + |
| 45 | +export default Prisma.defineExtension({ |
| 46 | + name: 'prisma-extension-pgpath-to-mysql', |
| 47 | + query: { |
| 48 | + $allModels: { |
| 49 | + findFirst: overriddenOperation, |
| 50 | + findMany: overriddenOperation, |
| 51 | + updateMany: overriddenOperation, |
| 52 | + count: overriddenOperation, |
| 53 | + deleteMany: overriddenOperation, |
| 54 | + |
| 55 | + delete: overriddenOperation, |
| 56 | + findUnique: overriddenOperation, |
| 57 | + update: overriddenOperation, |
| 58 | + upsert: overriddenOperation, |
| 59 | + } |
| 60 | + } |
| 61 | +}) |
0 commit comments