|
| 1 | +import { getDefaultModelMeta } from './model-meta'; |
| 2 | +import { withOmit, WithOmitOptions } from './omit'; |
| 3 | +import { withPassword, WithPasswordOptions } from './password'; |
| 4 | +import { withPolicy, WithPolicyContext, WithPolicyOptions } from './policy'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Options @see enhance |
| 8 | + */ |
| 9 | +export type EnhancementOptions = WithPolicyOptions & WithPasswordOptions & WithOmitOptions; |
| 10 | + |
| 11 | +let hasPassword: boolean | undefined = undefined; |
| 12 | +let hasOmit: boolean | undefined = undefined; |
| 13 | + |
| 14 | +/** |
| 15 | + * Gets a Prisma client enhanced with all essential behaviors, including access |
| 16 | + * policy, field validation, field omission and password hashing. |
| 17 | + * |
| 18 | + * It's a shortcut for calling withOmit(withPassword(withPolicy(prisma, options))). |
| 19 | + * |
| 20 | + * @param prisma The Prisma client to enhance. |
| 21 | + * @param context The context to for evaluating access policies. |
| 22 | + * @param options Options. |
| 23 | + */ |
| 24 | +export function enhance<DbClient extends object>( |
| 25 | + prisma: DbClient, |
| 26 | + context?: WithPolicyContext, |
| 27 | + options?: EnhancementOptions |
| 28 | +) { |
| 29 | + let result = prisma; |
| 30 | + |
| 31 | + if (hasPassword === undefined || hasOmit === undefined) { |
| 32 | + const modelMeta = options?.modelMeta ?? getDefaultModelMeta(); |
| 33 | + const allFields = Object.values(modelMeta.fields).flatMap((modelInfo) => Object.values(modelInfo)); |
| 34 | + hasPassword = allFields.some((field) => field.attributes?.some((attr) => attr.name === '@password')); |
| 35 | + hasOmit = allFields.some((field) => field.attributes?.some((attr) => attr.name === '@omit')); |
| 36 | + } |
| 37 | + |
| 38 | + if (hasPassword) { |
| 39 | + // @password proxy |
| 40 | + result = withPassword(result, options); |
| 41 | + } |
| 42 | + |
| 43 | + if (hasOmit) { |
| 44 | + // @omit proxy |
| 45 | + result = withOmit(result, options); |
| 46 | + } |
| 47 | + |
| 48 | + // policy proxy |
| 49 | + result = withPolicy(result, context, options); |
| 50 | + |
| 51 | + return result; |
| 52 | +} |
0 commit comments